33

In Javascript window.pageYOffset and document.documentElement.scrollTop both measures the distance of an window top to its topmost visible content in pixel. Are they both same or am I missing something?

Trust window.pageYOffset is not supported for IE < 9 but if assuming IE >8 then

  • When to use each of them
  • difference between them
Ahmet Emre Kilinc
  • 5,489
  • 12
  • 30
  • 42
jahajee.com
  • 3,683
  • 4
  • 21
  • 26
  • There's also [window.scrollY](http://stackoverflow.com/questions/3791336/why-were-window-scrolly-and-window-scrollx-introduced). – Dan Dascalescu Jul 21 '15 at 07:59

3 Answers3

21

Both window.pageYOffset and document.documentElement.scrollTop returns the same result in all the cases.

Yes, window.pageYOffset is not supported below IE 9.

scrollTop() method also can be used to get the vertical scrollbar position of the specific element.

Samuel Katz
  • 24,066
  • 8
  • 71
  • 57
Krish
  • 347
  • 1
  • 7
  • 3
    Apparently, `window.pageYOffset` is slower. A PR in claim: https://github.com/w3c/respec/pull/1685. Someone needs to create a jsperf for this. – Sid Vishnoi May 29 '18 at 09:55
11

The difference between these two can be clearly observed in cross platform mobile application development using Jquery mobile. There, several pages can be defined in single html pages.

document.documentElement.scrollTop will be useful when you are in a particular page and want the value relative to that page where as window.pageYOffset only applied to whole html page.

Otherwise like krish has mentioned, results from these two are basically the same.

Hashan Seneviratne
  • 1,157
  • 13
  • 24
2

document.documentElement.scrollTop does NOT work with Safari nor Apple Products.

window.pageYOffset works on all browsers. On browsers that support both functions, they appeared to produce the same values.

thedanotto
  • 6,895
  • 5
  • 45
  • 43
  • `document.documentElement` seems to be supported in Safari: https://developer.mozilla.org/en-US/docs/Web/API/Document/documentElement and so does `Element.scrollTop`: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop so I'm unsure where the claim that it doesn't work on Safari or other Apple Products comes from. – Alexander Varwijk Jan 11 '21 at 15:50
  • lol I'm too interested to know where that comes from? I see many people gives answers like that without proof, you should consider removing your answer as it will confuse a lot of people – medBouzid Jun 07 '22 at 11:20