Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 790
CR47 Avatar asked May 12 '13 04:05

CR47


2 Answers

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>

like image 100
Tieson T. Avatar answered Sep 24 '22 22:09

Tieson T.


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 :)

like image 37
Karl-André Gagnon Avatar answered Sep 24 '22 22:09

Karl-André Gagnon