It's Christmas, get a 30% OFF. Apply code XMAS at checkout.
Today we are starting a new series of tutorials, but with a twist. We are leaving Alpinejs behind and instead using vainilla JavaScript to create our components.
A scroll progress bar is a bar that shows the progress of the user’s scrolling through a page. It is typically used to indicate the amount of content that has been scrolled and the remaining amount of content to be scrolled. The scroll progress bar can be used to provide feedback to the user about their scrolling experience and to help them understand how much content is left to read.
and many similar use cases.
id="scroll-progress
: This is the id of the scroll progress bar.bg-orange-600
: This is the background color of the scroll progress bar. You can change this to any color you like.h-1
: This is the height of the scroll progress bar. You can change this to any height you like.fixed top-0 left-0
: This makes the scroll progress bar fixed to the top of the page and left-aligned.z-50
: This makes the scroll progress bar appear on top of other elements on the page.<div
id="scroll-progress"
class="bg-orange-600 h-1 fixed top-0 left-0 z-50">
</div>
window.addEventListener("scroll", function () {
: This is the event listener that listens for scroll events.const scrollableHeight = document.documentElement.scrollHeight - window.innerHeight;
: This calculates the total height of the scrollable content on the page.const scrolled = window.scrollY;
: This calculates the current scroll position of the page.const progressBar = document.getElementById("scroll-progress");
: This gets the scroll progress bar element.const progress = (scrolled / scrollableHeight) * 100;
: This calculates the progress of the scroll position.progressBar.style.width = progress + "%";
: This sets the width of the scroll progress bar to the calculated progress.window.addEventListener("scroll", function () {
const scrollableHeight =
document.documentElement.scrollHeight - window.innerHeight;
const scrolled = window.scrollY;
const progressBar = document.getElementById("scroll-progress");
const progress = (scrolled / scrollableHeight) * 100;
progressBar.style.width = progress + "%";
});
This is a simple scroll progress bar that uses Tailwind CSS and JavaScript to create a progress bar that shows the user’s scrolling progress. It’s a great way to add a visual cue to the user’s scrolling experience and to help them understand how much content is left to read. You can customize the progress bar to fit your needs and use it in your own projects, or you can use it as a starting point for your own scroll progress bars.
While this is created with JavaScript, you can also do it with plain CSS or Tailwind CSS if you prefer.
Hope you enjoyed this tutorial and have a great day!
/Michael Andreuzza
Unlock all themes for $199 for forever! Includes lifetime updates, new
themes, unlimited projects, and support. No subscription needed.
— No subscription required!