Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is body.scrollTop deprecated?

It seems body.scrollTop (and body.scrollLeft) are deprecated in ES5 strict-mode. What is the reason for this, given that it still seems okay to use these properties on other DOMElements?

Background Info:

I have a function that tries to increase (or decrease, as specified) the scrollTop values of all the ancestors of an element, till one of these actually changes. I am wondering if, to stay complaint with strict-mode, I should specifically check against the body element as the chain of parents moves upward.

[Obviously, bodyrefers to document.body]

like image 736
Himanshu P Avatar asked Oct 28 '13 12:10

Himanshu P


People also ask

Is scrollTop deprecated?

scrollTop is deprecated in strict mode.

Why is scrollTop not working?

If your CSS html element has the following overflow markup, scrollTop will not function. To allow scrollTop to scroll, modify your markup remove overflow markup from the html element and append to a body element.

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 .

Can I use document documentElement scrollTop?

Generally you can use (document. documentElement. scrollTop || document. body.


2 Answers

It's Chrome's own incorrect behavior that is deprecated, and they're warning authors to stop relying on it.

The scrolling viewport is represented by document.documentElement (<html>) in standards mode or <body> in quirks mode. (Quirks mode emulates the document rendering of Navigator 4 and Explorer 5.)

Chrome uses body.scrollTop to represent the viewport's scroll position in both modes, which is wrong. It sounds like they want to fix this so they're encouraging authors to script for the standard behavior.

I don't think you need to change your code. There's nothing wrong with using body.scrollTop in standards mode so long as you understand it represents the scroll position of body only (typically 0, unless you've given body a scroll box).

You can see the warning by executing document.body.scrollTop in the console:

body.scrollTop is deprecated in strict mode. Please use documentElement.scrollTop if in strict mode and body.scrollTop only if in quirks mode.

like image 56
sam Avatar answered Sep 24 '22 03:09

sam


I noticed my code stop working on newer versions of Chrome. I fixed it by using window.scrollY

Before:

var scrollTop = document.body.scrollTop; 

Now:

var scrollTop = window.scrollY; 

It works all the time now. You can find more documentation here.

Also, I was using:

document.body.scrollTop = 0; 

now I replaced it with:

window.scrollTo(0, 0); 
like image 37
Adrian Avatar answered Sep 26 '22 03:09

Adrian