0

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

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

Nice! Thank you. Yeah sorry I am just starting with jQuery. But your solution makes a lot of stuff more clear for me. Thanks.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.