How can I create a function in jQuery and call it?
This doesn't seems to be correct:
var scrollLink = function() {
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top-20
}, 300);
};
$('.js-ask').click(function(e) {
e.preventDefault();
$('[href="' + this.dataset.target + '"]').tab('show');
reportReadMessages();
});
$(".js-scroll").click(function(e, scrollLink) {
e.preventDefault();
scrollLink();
});
asked Dec 9, 2015 at 16:32
brunodd
2,59412 gold badges46 silver badges69 bronze badges
1 Answer 1
You aren't passing what is this in the scrollLink(). It is a function with empty parameters, when it doesn't understand what this is. So please change it to:
$('.js-ask').click(function(e) {
e.preventDefault();
$('[href="' + this.dataset.target + '"]').tab('show');
reportReadMessages();
});
$(".js-scroll").click(function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top-20
}, 300);
});
You are not passing the scrollLink in the right way. That's why it didn't work.
Or you can extend the function this way:
$.fn.scrollLink = function() {
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top-20
}, 300);
};
And you can call on the elements like:
$(this).scrollLink();
$(selector).scrollLink();
See How to add a function to jQuery? for more information.
answered Dec 9, 2015 at 16:35
Praveen Kumar Purushothaman
167k27 gold badges215 silver badges262 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
brunodd
Nice! Thank you. Yeah sorry I am just starting with jQuery. But your solution makes a lot of stuff more clear for me. Thanks.
lang-js