0
(0)

Just with a few line of Javascript a coloured indicator can be created to indicate how much did we already scrolled from the entire document.

The scroll indicator will be a progress tag, the value attribute will represent the current scroll distance already covered and the max attribute will have the maximum scroll distance coverable in the entire document.

Basically we will create a progress element with Javascript, that will have the class name and id the name “scrollProgressBar”. When we scroll down the value get’s increased till it reaches the max value and then the entire width is filled with a colour.

Let me provide you first with the CSS and Javascript code.

CSS first:

.scrollProgressBar {
  appearance: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
}
.scrollProgressBar::-webkit-progress-bar  {
  background: transparent;
}
.scrollProgressBar::-webkit-progress-value {
  background: red
}

Javascript code:

const scrollProgressBar = document.createElement('progress');
const scrollSize = document.documentElement.scrollHeight - document.documentElement.clientHeight;

scrollProgressBar.id = 'scrollProgressBar';
scrollProgressBar.className = 'scrollProgressBar';
scrollProgressBar.max = scrollSize;
document.body.appendChild(scrollProgressBar);

window.addEventListener('scroll', () => {
  const scrollPos = window.pageYOffset;
  
  document.getElementById('scrollProgressBar').value = scrollPos;
});
window.addEventListener('resize', () => {
    const newScrollSize = document.documentElement.scrollHeight - document.documentElement.clientHeight;
    document.getElementById('scrollProgressBar').max = newScrollSize;
})

We don’t have to add anything to the HTML file, everything is taken care of by our Javascript.

First we create our progress tag and add the class, id, and max attributes to it and we insert into the body.

In order to know what is the total scroll height we substract from the scroll height of the HTML, the height of the HTML. Why? Because when the scroll is on the 0 position we already see an entire screen/window from that document. This means when get to the end of the document, the scroll top will be less with a screen height. I mean imagine having the bottom of the document disappearing on the top of the screen and below would come the VOID. That doesn’t happen. What happens is, you can scroll till the last content appears.

The progress bar update will happen on the scroll event. The value attribute on the progress tag will be updated on every scroll movement.

We also need to take care of the situation when we resize the window. Then the max attribute’s value must change.

We recalculate the scroll height and apply a new value on the max attribute.

And that is it ! Enjoy.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Categorized in: