12

I am building a web app, and part of that web app needs to scroll to the top when an action is performed. This is handled using window.scrollTo(0,0) which works perfectly until I add some CSS styling below (which I require for this project).

Has anybody got any idea why the CSS below would stop window.scrollTo(0,0) working?

* {
    -webkit-transform: translate3d(0,0,0);
    -moz-transform: translate3d(0,0,0);
    -ms-transform: translate3d(0,0,0);
    -o-transform: translate3d(0,0,0);
    transform: translate3d(0,0,0);
}

P.S. I cannot use jQuery in my situation, just in case it's suggested that I do that.

user1873468
  • 477
  • 1
  • 4
  • 11

8 Answers8

35

I had the same problem, this fixed it:

document.getElementById('ELEMENT_ID').scrollIntoView();

Where ELEMENT_ID is the id of the object you want to scroll into view, in your case it would typically be the header.

Note this only works fully on Firefox browsers as the other browsers have yet to implement the smooth scrolling option (see more: http://caniuse.com/#feat=scrollintoview).

BlueEyesWhiteDragon
  • 427
  • 1
  • 6
  • 20
Josue Alexander Ibarra
  • 8,269
  • 3
  • 30
  • 37
14

Try the alternative :

document.body.scrollTop = 0;
basarat
  • 261,912
  • 58
  • 460
  • 511
10

I my case removing this block fixed the issue

html, body {
  overflow-x: hidden;
}
Dima
  • 1,045
  • 14
  • 23
5

Turns out there was not a set height on the main element in the body, which meant scroll to wasnt working however the transition CSS was giving the element height automatically in webkit.... Fixed the CSS to give it a set height and it works again!

user1873468
  • 477
  • 1
  • 4
  • 11
  • Just had an issue with scrollTo not working, also down to the height not being set on the body element. Thanks for posting your final solution – Phil Ostler Jan 14 '14 at 12:22
1

Changing

html, body {
  overflow-x: hidden;
}

to

body {
  overflow-x: hidden;
}

worked for me

reubano
  • 5,087
  • 1
  • 42
  • 41
1

I had this same issue recently in a Gatsby project. I had tried wrapping in setTimeout with no success.

What ended up working for me was window.scrollTo(0, -1).

jfgilmore
  • 73
  • 8
0

I found also that adding the following CSS caused the window.scroll() and window.scrollTo() methods to have no effect.

body {
    scroll-behavior: smooth;
}
Oleg Barabanov
  • 2,468
  • 2
  • 8
  • 17
0

Adding to @basarat's answer. It worked perfectly!

I did it in React, but in a function it's working and has smooth scroll.

    const scrollToTop = () => {
      document.body.scrollTo({ top: 0, behavior: "smooth" });
   };
Nethol
  • 1