All Posts
Published: June 26, 2023
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:
var scrollTop = document.documentElement.scrollTop;
– This line retrieves the current vertical scroll position of the page and assigns it to thescrollTop
variable.document.documentElement
refers to the root element of the document, which is usually the<html>
element.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 thescrollHeight
variable.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 thescrollPercentage
variable.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.