3

I'm hoping someone can explain to me this odd behavior I'm seeing with window.scrollTo.

This doesn't work.

document.addEventListener('DOMContentLoaded', function() {
    console.log('window.scrollY = ', window.scrollY);
    window.scrollTo(0, 200)
    console.log('window.scrollY = ', window.scrollY);
});

... well it does work, sort of ...

It works for the initial page load, but not refreshes (cmd + shift + r)...

The console output is:

window.scrollY = 0
window.scrollY = 200

So in that sense its working... except the page isn't scrolled, and when you type window.scrollY into the dev console it does indeed show 0.

So it would appear that the scroll is being set too early?

Where I get real confused is here:

var delay_ms = 0;

document.addEventListener('DOMContentLoaded', function() {
    setTimeout(function() {
        window.scrollTo(0, 200);
    }, delay_ms);
});

SOMEHOW THAT WORKS, but not consistently.

However...

var delay_ms = 10;

Increasing the delay, even by only 10ms, improves the consistently dramatically! To the point where it hasn't failed on me yet.

At first I thought maybe DOMContentLoaded was simply too early for height to be properly evaluated, so I switched the event I was listening for to:

window.addEventListener('load', function() { /* ... */ });

According to the MDN Docs for .onload

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.

So I can't imagine what would be setting the scroll to 0, after I'm setting it to 200...

Does anyone have any insight into what is happening with this timing?

Covering my bases

  • Yes there is space to scroll.
  • Here's a gist with some full reproduction code.
  • I'm on a mac, using chrome.
piratematt
  • 133
  • 5
  • 3
    Some browsers attempt to automatically scroll the page to the last known position on a page refresh, unfortunately this happens after the load events have fired. See [here](http://stackoverflow.com/questions/18617367/disable-browers-auto-scroll-after-a-page-refresh) for a few workarounds. – Jordan Burnett Dec 19 '16 at 17:31
  • Ah that would explain why its only happening on reload and not original navigation! I wonder how this plays with the standard pattern, where href's link to element Ids. – piratematt Dec 27 '16 at 14:17

0 Answers0