How to Create Scroll Indicator

How to Create Scroll Indicator using HTML, CSS, and JavaScript?

Have you noticed that as you scroll down the page, there is a scrollbar at the top of every page?

A scroll indicator is a bar that shows how far down a page has been scrolled. The bar fills up as we scroll down, and as we scroll up, the bar quantity decreases.


Or this scrollbar displays the amount of length you’ve covered scrolling down the page. Scroll position indications include variations on the vertical scrollbar, horizontal components at the top or bottom of the page, and other styles.

Now we’ll develop a simple web page with text to allow scrolling, and then we’ll use JavaScript to make the scroll indicator work.

This example shows you how to create a scroll indicator for your website using a little JavaScript code.

<div id="progress-bar"></div>
<div id="section"></div>

<!-- your main content here -->

</div>

Add Styles to the progress bar

body {
    overscroll-behavior-y: none;
}
#progress-bar {
    position: fixed;
    top: 0;
    left: 0;
    height: 0.2rem;
    background: linear-gradient(to right, #ff5f6d, #ffc371);
    width: 0%;
    max-width: 100%;
    min-width: 0%;
    z-index: 100;
    transition: width 0.2s ease-out;
}

Finally, add some JavaScript code

const animateProgressBar = () => {

    var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
    var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
    var scrolled = (winScroll / height) * 100;
    document.getElementById("progress-bar").style.width = scrolled + "%";

}

window.addEventListener('scroll', animateProgressBar);

Demo of the Scroll Indicator

See the Pen Scroll Indicator by niat (@niat786) on CodePen.

How to change the color and height of the Scroll Indicator?

You can also change the color and height of the progress bar. Just modify the CSS properties of the id #progress-bar

#progress-bar {
    height: 0.5rem;
    background: linear-gradient(to right, #ff5f6d, #ffc371);
}

Read also: How to create a beautiful ” before and after image slider ” JavaScript