Create a Scroll Indicator with CSS and JavaScript
Scroll indicator indicates and animates accordingly. When the scroller goes down, the progess bar suggests how many elements are still remaining. When the scroller takes you to the bottom, the scroll indicator i.e., the progress bar also ends. Let us see how to create a scroll indicator with CSS and JavaScript.
Fixed header
First, set the position of the header to be fixed using the position property with the value fixed. The header will remain fixed even when the web page navigates to the bottom −
.header { position: fixed; top: 0; margin-bottom: 100px; z-index: 1; width: 100%; background-color: #ebfffd; }
Create a Progress Bar
For the scroll indicator, use a progress bar −
<div class="progressContainer"> <div class="progressBar"></div> </div>
Style the progress bar
Set the width of the progress bar container with the height. The container width is set to 100% −
.progressContainer { width: 100%; height: 20px; background: #ccc; }
Initial Progress Bar
The initial width of the progress bar is set to 0% because when the web page loads it is at the top −
.progressBar { height: 20px; background: #724caf; width: 0%; }
Set the div for the content
For the content on the web page, create a div −
<div class="content"> <h2>Some headers</h2> <h2>Some headers</h2> <h2>Some headers</h2> <h2>Some headers</h2> <h2>Some headers</h2> </div>
Example
To create a scroll indicator with CSS and JavaScript, the code is as follows −
<!DOCTYPE html> <html> <head> <style> body { font-size: 28px; margin:0px; padding:0px; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } .header { position: fixed; top: 0; margin-bottom: 100px; z-index: 1; width: 100%; background-color: #ebfffd; } .progressContainer { width: 100%; height: 20px; background: #ccc; } .progressBar { height: 20px; background: #724caf; width: 0%; } .content { padding: 100px 0; margin: 50px auto 0 auto; width: 80%; } </style> </head> <body> <div class="header"> <h1>Scroll indicator example</h1> <div class="progressContainer"> <div class="progressBar"></div> </div> </div> <div class="content"> <h2>Some headers</h2> <h2>Some headers</h2> <h2>Some headers</h2> <h2>Some headers</h2> <h2>Some headers</h2> </div> <script> window.onscroll = function() {showProgress()}; function showProgress() { var scrollCalculate = document.body.scrollTop || document.documentElement.scrollTop; var height = document.documentElement.scrollHeight - document.documentElement.clientHeight; var scrolled = (scrollCalculate / height) * 100; document.querySelector(".progressBar").style.width = scrolled + "%"; } </script> </body> </html>