how to prevent browsers auto scroll on reload with javascript?

13,340

Here's a solution that works in FF (18), Chrome (24) and IE (9).

Putting the following in a script in the head section of your document:

function autoScroll() {
    var div = document.getElementById("mydiv");
    div.style.display = '';
    var top = div.offsetTop;
    if(window.scrollTop != top) 
        window.scrollTo(0, top);
}
function loadAutoScroll() {
    autoScroll();
    window.onload = null;
    return false;
}
function scrollAutoScroll() {
    autoScroll();
    window.setTimeout(function(){ window.onscroll = null; }, 100);
    return false;
}
window.onload = loadAutoScroll;
window.onscroll = scrollAutoScroll;

I'm sure a cleaner solution can be derived.

Share:
13,340

Related videos on Youtube

dgeare
Author by

dgeare

Updated on September 15, 2022

Comments

  • dgeare
    dgeare over 1 year

    So, nowadays most browsers will automatically reposition the window scroll on page refresh, which is normally great, but I have a situation where I need to reload a page and focus on a different part of the page from where the user left. NOTE the new element which gets focus starts as hidden, so a hash WON'T work. I need to handle it in JS so I can make the div visible, among other things.

    called after reload...

    $(document).ready(function(){
        $('#mydiv').show();
        var top = $('#myelement').offset().top;
        window.scrollTo(0, top);
    });
    

    Nonetheless, the page focuses on the place the user left the page from. After much debugging, it seems to me that the code works well enough, but the browser is handling the reload event AFTER I do, and re-positioning my newly positioned scroll... It happens instantaneously, but if I place an alert just after my scroll, it shows the proper screen location. After dismissing the alert, the browser jumps the scroll back to where IT thinks it should be (at least in Chrome it does).

    My question, is there any way to prevent the browser (cross-browser) from handling the reload event? delaying my scroll with a timeout seems to work, but it looks very unprofessional and jumpy.

    I've tried

        $(document).unbind("scroll"); 
    

    as I saw recommended somewhere here, but it didn't do anything.

    Thanks, in advance, for any help.

  • dgeare
    dgeare about 11 years
    It works. thank you very much for your efforts. ^_^