Reputation: 2584
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();
});
Upvotes: 0
Views: 77
Reputation: 167240
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.
Upvotes: 4