Scrolling overflowing elements with JavaScript
HTML elements with overflow-y: auto
or overflow-y: scroll
will get a scrollbar when their content is higher than their own height.
When you scroll an element , the element's scrollTop
property is updated with the scrollbar's new position. You can also set element.scrollTop = 30
to scroll the element to a vertical pixel position counted from the top.
Scrolling the main viewport with JavaScript
The browser's main document viewport is also scrollable by default. The element that corresponds to the main viewport is either <html>
(document.documentElement
) or <body>
(document.body
). Which one depends on the browser.
When you want to update the current scrollTop
of the main viewport, you either need to find the correct element or set scrollTop
on both <body>
and <html>
.
Finding the scrolling element
Your JavaScript can call
document.scrollingElement
Show archive.org snapshot
to retrieve the scrollable element for the main viewport.
The behavior of document.scrollingElement
varies between browsers:
- On Chrome and Firefox,
document.scrollingElement
will return the<html>
element. - Safari,
document.scrollingElement
will return the<body>
element. - On Edge,
document.scrollingElement
will return the<body>
element. - IE11 does not support
document.scrollingElement
, but you can assume its<html>
.
Summing up, this function should return the correct element on current browsers:
function scrollingElement() {
return document.scrollingElement || document.documentElement;
}
Setting overflow-y for the main viewport with CSS
You can set overflow-y
on either <html>
or <body>
and browsers will silently apply it to whatever scrolling element their implementation uses.
Don't set overflow-y
for both <html>
and <body>
or funny things will happen.
Setting overflow-y for the main viewport with JavaScript
When your JavaScript wants to change overflow-y
for the main viewport, you should change it on the same element that already has this property set in its CSS styles. Note that this element must not necessarily be the same as scrollingElement()
above.
If you have no control over the CSS styles, your script must look for the right element:
- If
<html>
has anoverflow-y
of eitherscroll
orauto
, use<html>
. - If
<body>
has anoverflow-y
of eitherscroll
orauto
, use<body>
. - If neither has an
overflow-y
set, use<html>
.