Reading position indicator with JQuery

Many websites (especially blogs) have a scroll position indicator, which helps users understand how far they are from finishing the article. I will call this feature a Progress Meter.

This Progress Meter can be horizontal or vertical, but there are some more creative ideas too. I will show you how to create an horizontal progress meter.

Let's start with the HTML:

<div class="section">  
      <h3>First Section</h3>
      Some content here ... 
</div>  
<div class="section">  
      <h3>Second Section</h3>
      Some content here ... 
</div>  
<div class="section">  
      <h3>Third Section</h3>
      Some content here ...
</div>  
...

So each section we want to be indicated on the progress meter will have the same class, .section.

The next step is to create the indicator, with jQuery:

$(document).ready(function() {
  if ($('.section').length > 0) {
    $('body').append('<div class="progress-meter"></div>');

    for (var i = 0; i < $('.section').length; i++) {
      $('.progress-meter').append('<div class="indicator' + i + '"></div>');
    }

    var diff = $('.section').eq(0).offset().top;

    $(document).on('scroll', function() {
      for (var i = 0; i < $('.section').length; i++) {
        var offset = $('.section').eq(i).offset();

        if (offset) {
          var distance = offset.top - diff + 5,
            top = $(document).scrollTop(),
            windowHeight = $(window).height(),
            docHeight = $(document).height();

          if ((distance <= top) || (top + windowHeight == docHeight)) {
            $('.indicator' + i).addClass('reached');
          }
          else if ($('.indicator' + i).hasClass('reached')) {
            $('.indicator' + i).removeClass('reached');
          }
        }
      }
    });
  }
});

So for each section we will create an indicator on the progress meter. On the scroll event we are recalculating the offset of each section from the top, and if a section is reached, its indicator will be coloured accordingly.

Let's do some styling too:

.progress-meter {
  position: fixed;
  top: 5px;
  left: 5px;
}
.progress-meter div[class^="indicator"] {
  float: left;
  width: 150px;
  height: 15px;
  margin: 0 2px;
  background-color: rgba(0, 102, 102, 0.3);
  border: 1px solid rgba(0, 102, 102, 0.4);
}
.progress-meter div[class^="indicator"].reached {
  background-color: rgba(0, 102, 102, 1);
}

Note the div[class^="indicator"] selector. It refers to divs which classes are starting with "indicator". (In our case, indicator1, indicator2, and so on.)

You can see a demo on codepen.

Any opinions are welcome :) !