How to create a scroll indicator with CSS and JavaScript?

CSSWeb DevelopmentFront End TechnologyJavascript

To create a scroll indicator with CSS and JavaScript, the code is as follows −

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<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">
<h1>Some headers</h1>
<h1>Some headers</h1>
<h1>Some headers</h1>
<h1>Some headers</h1>
<h1>Some headers</h1>
</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>

Output

The above code will produce the following output −

On scrolling down the page the progress bar will increase as shown −

raja
Published on 07-May-2020 11:00:24
Advertisements