Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.documentElement.scrollTop return value differs in Chrome

I am trying to process some code based on the 'document.documentElement.scrollTop' value. It returns '348' in FF and IE but in Chrome it returns '0'. Do i need to do anything to overcome this issue?

FF:

>>> document.documentElement.scrollTop 342 

Chrome:

document.documentElement.scrollTop 0 
like image 440
RGR Avatar asked Dec 11 '13 08:12

RGR


People also ask

Is scrollTop deprecated?

scrollTop is deprecated in strict mode.

What is Document body scrollTop?

scrollTop property gets or sets the number of pixels that an element's content is scrolled vertically. An element's scrollTop value is a measurement of the distance from the element's top to its topmost visible content. When an element's content does not generate a vertical scrollbar, then its scrollTop value is 0 .

What is documentElement?

documentElement returns the Element that is the root element of the document (for example, the <html> element for HTML documents).


2 Answers

The standards-based way of getting the scroll is window.scrollY. This is supported by Chrome, Firefox, Opera, Safari and IE Edge or later. If you only support these browsers, you should go with this property.

IE >= 9 supports a similar property window.pageYOffset, which for the sake of compatibility returns the same as window.scrollY in recent browsers, though it may perhaps be deprecated at some point.

The problem with using document.documentElement.scrollTop or document.body.scrollTop is that the scroll needn't be defined on either of these. Chrome and Safari define their scroll on the <body> element whilst Firefox defines it on the <html> element returned by document.documentElement, for example. This is not standardized, and could potentially change in future versions of the browsers. However, if the scrollY or pageYOffset are not present, this is the only way to get the scroll.

TL;DR:

window.scrollY || window.pageYOffset || document.body.scrollTop + (document.documentElement && document.documentElement.scrollTop || 0)

like image 84
jazmit Avatar answered Oct 07 '22 20:10

jazmit


Try this

window.pageYOffset || document.documentElement.scrollTop 
like image 43
Nick Salloum Avatar answered Oct 07 '22 18:10

Nick Salloum