Skip to main content

Page Scroll Progress Bar using JavaScript

Submitted by admin on Fri, 07/22/2022 - 21:58
Page Scroll Progress Bar using JavaScript

In this JavaScript tutorial, we will create a page scroll progress bar. This progress bar will indicate the scroll percentage of the current page.

We will keep the progress bar at the top of the page using position: fixed and a higher z-index value.

Step 1: HTML


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

Step 2: CSS


#page-progress-bar {
  position: fixed;
  top: 0;
  left: 0;
  width: 0%;
  height: 8px;
  background: linear-gradient(to right, #5B61ED, #B788E5);
	z-index: 99;
}

Step 3: JavaScript


const pageProgressBar = document.getElementById('page-progress-bar');
const pageContent = document.getElementById('page')
const pageContentHeight = pageContent.offsetHeight;
const winHeight = window.outerHeight;
const scrollHeight = pageContentHeight - winHeight;

const animatePageProgressBar = () => {
  scrollPosition = document.documentElement.scrollTop;
  barWidth = (100 / scrollHeight) * scrollPosition;
  pageProgressBar.style.width = (barWidth +'%');
}

window.addEventListener("scroll", animatePageProgressBar)

Thank you for reading, and let's connect!

Thank you for reading my post. Feel free to connect on Twitter, GitHub and Linkedin

Category

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.