RayCC
Cover Image

Scroll indicator in JS

1 min

Js Javascript Snippet

Source: https://www.w3schools.com/howto/howto_js_scroll_indicator.asp

HTML

1
2
3
<div class="progress-container">
  <div class="progress-bar" id="myBar"></div>
</div>

JavaScript

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const myBar = document.getElementById("myBar");

document.addEventListener("DOMContentLoaded", function () {
  window.onscroll = function () {
    let winScroll = document.body.scrollTop || document.documentElement.scrollTop;
    let height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
    let scrolled = (winScroll / height) * 100;
    myBar.style.width = scrolled + "%";
  };
});

CSS

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
.progress-container {
  width: 100%;
  height: 1px;
  background: white;
  position: sticky;
  /* position: fixed; */
}

.progress-bar {
  height: 1px;
  background: black;
  width: 0%;
}