Posted 6 months ago. Visible to the public. Repeats.

Does <html> or <body> scroll the page?

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 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:

Copy
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:

  1. If <html> has an overflow-y of either scroll or auto, use <html>.
  2. If <body> has an overflow-y of either scroll or auto, use <body>.
  3. If neither has an overflow-y set, use <html>.

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Avatar
Henning Koch
Last edit:
about 1 month ago
by Besprechungs-PC
Keywords:
html, body
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more