March 24, 2012

How do I prevent auto-scrolling to the top in jQuery?

Question by Johnny

This works in all other browsers and I have no idea what the problem is. I’m kind of in a hurry so I thought I’d ask you guys in case I missed anything obvious. I have a link you click on which initiate a popup, and in Firefox (and possibly opera) the page auto scrolls back to the top.

    $('[class*=popup-link]').click(function(e) {

    /* Prevent default actions */
    e.preventDefault();
    e.stopPropagation();

    /* Get the id (the number appended to the end of the classes) */
    var name = $(this).attr('class');
    var id = name[name.length - 1];

    /* Show the correct popup box, show the blackout and disable scrolling */
    $('#popup-box-'+id).show();
    $('#blackout').show();
    $("html,body").css("overflow","hidden");

});

I need both preventDefault and stopPropagation to stop some other stuff happening. Can you see any errors or a way to stop this auto scrolling to the top? Thanks!

Quick Edit:

I’m also running a function which centers the box using

$(window).scroll(centerBox);

I’m unsure if this would affect scrolling in some odd way in firefox. The contents of this function are just adding CSS, so I doubt they would have any effect on it.

Another Edit:

A link to try it out. Not working in Firefox for me.
http://inserthtml.com/demo/internal-popup/

Answer by Joseph the Dreamer

first, i see nothing wrong in the script. it should be preventing the “top jump” even only with e.preventDefault(). try stripping it down to this. it should tell if this handler is causing it or not

$('[class*=popup-link]').click(function(e) {

    e.preventDefault();   //prevent the click from jumping esp on hashes
    e.stopPropagation();  //prevent from any parent click handlers that didn't prevent the jump

    //no code here for now

    return false;         //the natural way to prevent the jump
});

if this code prevents the jump, then there is something in the rest of your code that causes it especially broken scripts. check the console for errors also

Answer by Starx

e.preventDefault();
e.stopPropagation();

is equivalent to

return false;

Change them, and you will be fine

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!