CR47
CR47

Reputation: 923

JQuery scrollTop function goes to correct position but then jumps back to top of page

I used the JQuery function scrollTop on a list of contact numbers in a click function for each letter. It scrolls to where it is supposed to but then scrolls back to the top immediately.

Here is a sample of the function in the code:

$('.a').click(function(){
     $('html, body').animate({scrollTop:$('#A').position().top}, 'slow');
});

Here is the JSFiddle I made for it: http://jsfiddle.net/CR47/MdtSE/

Upvotes: 6

Views: 9945

Answers (2)

Tieson T.
Tieson T.

Reputation: 21201

If you're adding this to an anchor tag, you normally need to add a preventDefault() or return false; to cancel the navigation event.

So:

$('.a').on('click', function(e){
    e.preventDefault();
    $('html, body').animate({scrollTop:$('#A').position().top}, 'slow');
});

or

$('.a').on('click', function(e){
    $('html, body').animate({scrollTop:$('#A').position().top}, 'slow');
    return false;
});

I also updated your sample to use the recommended syntax from jQuery 1.8+.

EDIT: As @Karl-Andre Gagnon points out:

return false work because it prevent the event from bubbling since preventDefault prevent the default action of the element. Since a click on a span has no default action, it does nothing!

So the first example will only really work if you're using something like

<a href="#" class="a">Back to top</a>

Upvotes: 11

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

You writted the "a" span like that :

<span class="a">A</spam>

Due to this typo, it is not closed. That's causing every click (on any letter) to be a click on the "a" after bubbling.

Just change the "m" for a "n" and everything work fine.

Those damn typos, messing up the entire code :)

Upvotes: 1

Related Questions