Johnny
Johnny

Reputation: 9964

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

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/

Upvotes: 1

Views: 9097

Answers (2)

Starx
Starx

Reputation: 78971

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

is equivalent to

return false;

Change them, and you will be fine

Upvotes: 1

Joseph
Joseph

Reputation: 119827

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

Upvotes: 2

Related Questions