dgeare dgeare - 1 year ago 146
Javascript Question

how to prevent browsers auto scroll on reload with javascript?

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...

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


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

Thanks, in advance, for any help.

Answer Source

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

Putting the following in the HEAD.

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

I'm sure a cleaner solution can be derived.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download