As a front-end engineer, when building your own website, there must be an impulse to do DIY design for each module as you wish. For example, design a nice scrolling progress bar for your page while the browser is scrolling. According to the distance of the scroll, to dynamically display the progress of the scroll.

One, achieve the effect

Today I share a rainbow scroll progress bar that only takes a few lines of code to complete. The general appearance is shown in the figure below.

Two, the implementation principle

In fact, this function is very simple to say, the core is the page monitor scroll distance and can scroll percentage assigned to the progress bar width property.

(1) HTML & CSS

Fix the progress DOM to top:0 and set the width to 0%. Because we want to make the rainbow color, we set 7 DOM Settings with different colors, pull out their height properties, and set a unified CSS variable.

<div id="progress-bar">
    <div id="red"></div>
    <div id="orange"></div>
    <div id="yellow"></div>
    <div id="green"></div>
    <div id="blue"></div>
    <div id="indigo"></div>
    <div id="purple"></div>
</div>
Copy the code
:root {
  --progress-bar-height: 10px;
}

#progress-bar {
  width: 0%;
  position: fixed;
  top: 0;
  left: 0;
}

#red {
  background-color: #FF0000;
  height: var(--progress-bar-height); } // Other colors...Copy the code

(2) JavaScript

Before we get started, let’s get a general idea of what scrollHeight, clientHeight, and scrollTop represent.

  1. document.body.clientHeightThis is the web visible area
  2. document.body.scrollHeightIt’s the total height of the page
  3. document.body.scrollTopThat’s how far we’ve rolled

All we have to do is figure out how far the page can scroll, which is the number two minus the number one.

const needScroll = document.body.scrollHeight - document.documentElement.clientHeight;
Copy the code

Then listen for the scroll event to get the current scroll distance. Document.body. scrollTop is how far the scroll bar scrolls down, or how high the top of the element is covered.

window.addEventListener('scroll'.() = > {
  const haveScrolled = document.body.scrollTop || document.documentElement.scrollTop;
})
Copy the code

Finally, assign the width property to Progress by finding the percentage of scrolling.

progressBar.style.width = haveScrolled / needScroll * 100 + The '%';
Copy the code

This will be able to get the effect, here only brief principle, more effect, adaptation will not say more. In fact, we can not only make a horizontal progress bar, we can also make it into a ring, or like an Android phone charging effect, etc., it is up to us to invent.