JavaScript scrollTo method does nothing?

So I am desperatley trying to get some scrolling functionality to work on a page. After not having a luck I decide to just stick window.scrollTo(0, 800); on my page to see if I could get any scrolling to happen. Nothing does happen. I have an accordion that expands and then I want to scroll to a specific element with in it. But for now I would be happy to just see the thing scroll at all. Anyone run into this?

Thanks!


Solution 1:

If you have something like this:

html, body { height: 100%; overflow:auto; }

If both body and html have a height definition of 100% and also scrolling enabled, window.scrollTo (and all derived scrolling mechanisms) do not work, despite a scrollbar being displayed (which can be used by the user), when the contents exceed that 100% body height. This is because the scrollbar you see is not that of the window, but that of the body.

Solution:

html { height: 100%; overflow:auto; }
body { height: 100%; }

Solution 2:

I fixed this problem with using a setTimout. I was using angularjs but maybe it can help in vanilla js too.

        setTimeout(function () {
            window.scrollTo(0, 300);
        },2);

Solution 3:

I was able to resolve this problem using jQuery method animate(). Here is an example of the implementation I went with:

$('#content').animate({ scrollTop: elementOffset }, 200);

The selector is getting the div with ID = "content". I am then applying the animate method on it with scrollTop as an option. The second parameter is the time in milliseconds for the animation duration. I hope this helps someone else.

Solution 4:

Sometimes it's not just the CSS issue, for me the browser was the culprit. I had to solve it with this code:

if ('scrollRestoration' in window.history) {
  window.history.scrollRestoration = 'manual'
}

It lets developer take the ownership of scroll changes. Read more about it here

Solution 5:

This happened to me yesterday because I had overflow: auto on a div that was a child to <html> and <body>.

So I learned that for window.scrollTo() to work, you must have overflow: auto (or whatever, overflow-y: scroll) set on the <html> element.

I learned that for document.body.scrollTo() to work, you must have overflow set on <body>.

I learned you can also use it on any other element (if you want) using document.querySelector('#some-container').scrollTo().

In my case, I wanted window.scrollTo() to work, so I put the overflow CSS on <html>.

I'm surprised no other answers in here talk about "exactly which" element is scrollable. The root html element must be scrollable for window.scrollTo() to work. All my child elements downstream of <html> are set to height: auto.

My CSS is like this:

html { position: absolute; left: 0; top: 0; right: 0; bottom: 0; overflow: auto; }
body { width: 100%; height: auto; }
#app { width: 100%; height: auto; }