DEV Community

Pankaj yadav
Pankaj yadav

Posted on

How to create a left to right scroll-based navigation progress bar

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Scroll Progress Bar</title>
  <link rel="stylesheet" href="style.css" />
</head>
<body>

  <!-- ๐Ÿ”ต Progress Bar (Top) -->
  <div class="progress-bar"></div>

  <!-- ๐Ÿ”ฝ Page Content -->
  <div class="content">
    <h1>Scroll to See Progress</h1>
    <p>This is a demo of a scroll-based navigation progress bar. Scroll down to see the bar move.</p>

    <!-- Dummy content to create scroll -->
    <div style="height: 3000px;"></div>
  </div>

  <script src="script.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Now we give styles

body {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
}

/* Progress Bar Styles */
.progress-bar {
  position: fixed;
  top: 0;
  left: 0;
  width: 0%;
  height: 5px;
  background-color: #00bcd4;
  z-index: 9999;
  transition: width 0.25s ease-out;
}

/* Main Page Content */
.content {
  padding: 20px;
}
Enter fullscreen mode Exit fullscreen mode

and lastly we integrate js

window.addEventListener("scroll", () => {
  const scrollTop = document.documentElement.scrollTop;
  const scrollHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
  const scrollPercentage = (scrollTop / scrollHeight) * 100;

  document.querySelector(".progress-bar").style.width = scrollPercentage + "%";
});

Enter fullscreen mode Exit fullscreen mode

๐Ÿ” How It Works

  1. scrollTop: Kitna scroll hua hai

  2. scrollHeight: Total scrollable height

  3. clientHeight: Visible screen height

  4. scrollPercentage: Ye calculation top scroll bar ka width define karti hai

โœ… Output:
1.Aap scroll karte jaoge, to top me ek slim line move karti rahegi.

2.Ye visually batati hai ki aap kitna content scroll kar chuke ho.

Top comments (0)