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

CR47 picture CR47 · May 12, 2013 · Viewed 9.1k times · Source

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/

Answer

Tieson T. picture Tieson T. · May 12, 2013

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>