Skip to content Skip to sidebar Skip to footer

Why Does This Code Use Both `document.body` And `document.documentElement`?

Okay, so I'm trying to figure out how this JS code works.. Could you explain me some things? There's the code (I've copied some of the w3schools' code, full: https://www.w3schools

Solution 1:

From the question title pre-edit:

What's the difference between document.body and document.documentElement?

document.body is the body element. document.documentElement is (in HTML documents) the html element.

So why we need two variable setting in topFunction()?

Because unfortunately, when scrolling the content of the main window, some browsers have historically scrolled html, and others body. You can try your current browser here:

var n, div;
for (n = 1; n <= 100; ++n) {
  div = document.createElement('div');
  div.innerHTML = String(n);
  document.body.appendChild(div);
}
var bodyDisplay = document.getElementById("body-display");
var docElDisplay = document.getElementById("docel-display");

document.addEventListener("scroll", function() {
  bodyDisplay.innerHTML = String(document.body.scrollTop);
  docElDisplay.innerHTML = String(document.documentElement.scrollTop);
});
.top {
  position: fixed;
  height: 2em;
  border-bottom: 1px solid #ddd;
  background: white;
}
<div class="top">
  <div>
    body scrollTop:
    <span id="body-display"></span>
  </div>
  <div>
    documentElement scrollTop:
    <span id="docel-display"></span>
  </div>
</div>
<div>Scroll up and down</div>

Post a Comment for "Why Does This Code Use Both `document.body` And `document.documentElement`?"