Christian Wahl

Scrolling Window

12 Oct 2021 • Christian Wahl

This is a basic example of updating a page based on scrolling behaviour.

The variable height is the max value found among the various heights on both window and body. And in the event listener, the scrolled percentage is calculated based on the current scrollY, the height and the height of the visible window.

var body = document.body,
  html = document.documentElement;

var height = Math.max(body.scrollHeight, body.offsetHeight,
  html.clientHeight, html.scrollHeight, html.offsetHeight);

document.addEventListener('scroll', e => {
  var percentY = window.scrollY / (height - window.innerHeight);
  document.querySelector('#box').style.opacity = percentY;
  document.querySelector('#number').textContent = Math.round(percentY*100);
});

A bit of CSS:

body {
  height: 1200px;
}
#box {
  height: 100px;
  width: 100px;
  position: fixed;
  background: navy;
  opacity: 0;
}
#number {
  position: fixed;
  background: navy;
  color: white;
}

A bit of HTML:

<div id="box"></div>
<div id="number">0</div>

Here is a working example in an iframe: