Skip to main content

Tedshd's Dev note

JavaScript - Scroll Progress

Table of Contents

# JavaScript - Scroll Progress

Show a progress bar about page scroll position.

This used scroll event Progress bar must handle scroll position and scroll total height, and show it for percent View MDN document can find it can’t use scrollHeight, because when scroll bar scroll to bottom, scrollTop not equal scrollHeight

dom = document.querySelector("body");
percent =
  (dom.scrollTop / (dom.scrollHeight - document.documentElement.clientHeight)) *
    100 +
  "%";

Then find scrollTop didn’t work in firefox

if (dom.scrollTop) {
  percent =
    (dom.scrollTop /
      (dom.scrollHeight - document.documentElement.clientHeight)) *
      100 +
    "%";
} else {
  percent =
    (window.pageYOffset /
      (dom.scrollHeight - document.documentElement.clientHeight)) *
      100 +
    "%";
}

GitHub

Refer - onscroll event | scroll event Refer - Element.scrollTop - Web API Interfaces | MDN Refer - element.scrollHeight - Web API Interfaces | MDN Refer - retrieve Scrollbar position with javascript