All Posts

Build your own scroll depth progress bar for WordPress with this simple snippet

Published: June 26, 2023
Share:
Image

window.addEventListener('scroll', function() {
  var scrollTop = document.documentElement.scrollTop;
  var scrollHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
  var scrollPercentage = (scrollTop / scrollHeight) * 100;
  
  document.documentElement.style.setProperty('--scroll-depth', scrollPercentage + '%');
});

What’s happening? The code included above adds an event listener to the window object for the ‘scroll’ event. When the user scrolls the page, the function provided as the second argument will be executed.

Inside the function, the following steps are performed:

  1. var scrollTop = document.documentElement.scrollTop; – This line retrieves the current vertical scroll position of the page and assigns it to the scrollTop variable. document.documentElement refers to the root element of the document, which is usually the <html> element.
  2. var scrollHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight; – This line calculates the maximum scrollable height of the page by subtracting the height of the visible portion of the page (viewport) from the total height of the document. It assigns the result to the scrollHeight variable.
  3. var scrollPercentage = (scrollTop / scrollHeight) * 100; – This line calculates the scroll percentage by dividing the current scroll position (scrollTop) by the maximum scrollable height (scrollHeight), and then multiplying the result by 100. It assigns the calculated percentage to the scrollPercentage variable.
  4. document.documentElement.style.setProperty('--scroll-depth', scrollPercentage + '%'); – This line sets a CSS custom property (--scroll-depth) on the root element (document.documentElement) and assigns the calculated scroll percentage as its value. The % sign is appended to the scroll percentage to represent it as a valid CSS value.

The purpose of this code is to dynamically update a CSS custom property (--scroll-depth) based on the user’s scroll position. This custom property can then be used in CSS styles as seen in the video as the width of the div in Cornerstone to create a scroll depth progress effect.