Scrolling indicator for each section

Viewed 301

Ok, so I want to make a scroll indicator, that should start from 0 to 100 at each section. Each section is 100vh height. As it works right now, it will go from 0 to 100 when you have scrolled from top to the bottom through all of the sections. Lets say we have 4 sections, that is 100vh height, so basically, the counter should go from 0 to 400.

The way it works right now is

window.onscroll = function () { myFunction() };

function myFunction() {
  var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
  var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
  var scrolled = (winScroll / height) * 100;
  document.getElementById("myBar").style.width = scrolled + "%";

  console.log(winScroll);
}

The variable scrolled, will of course only go from 0 to 100 when it gets all the way through these four sections. Anyone who's up for a challenge?

A screenshot as example. Then the indicator at top should start from 0 again at next section enter image description here

I have tried to say scrolled * count_of_sections, but it gets 100% way before the section is done

Found the solutions by saying

document.getElementById("myBar").style.width = `calc(${scrolled * 3}% + 8px)`;

Only times 3 cause you can't scroll the last section and + 8px cause the height of the progress bar, if anyone is curious

0 Answers
Related