Programming Reading Position Indicator with jQuery & CSS

Programming Reading Position Indicator with jQuery & CSS Thumbnail
Published on 30. April 2019Last updated on 20. May 2020

Reading Progress Indicator, Scroll Position or Scroll Indicator: The mysterious bar has many names, but the best known is probably Reading Position Indicator. Here you can learn how to program this feature with jQuery and CSS.

Advertisement

The Reading Position Indicator is a popular feature for many sites, especially blogs with corresponding articles. This gives the reader a better idea of how long the article is still and it is often nice to look at. 🙂

Example Reading Position Indicator

For WordPress pages there are plugins available, but you will soon find that you can easily program this function yourself.

Advertisement

1. Prepare HTML structure

First we need the actual strip. For this we create a container which we later set to full width and a container inside which is always as long as the current progress should be. An example of this structure could look like this:

<div id="read-progress" class="progress">
  <div class="progress-bar"></div>
</div>

2. Style using CSS

If you have included Bootstrap in your site, you can use a ready-made progress bar and you can skip this step. You can find the link here.

But beware, there are some rules you should follow when using CSS!

If you want to write the CSS yourself, you can use this structure as a basic framework and adjust colors and thickness, for example:

Advertisement
.progress {
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  height: 5px;
  background-color: #d3d3d3;
}
.progress > .progress-bar {
  height: 5px;
  width: 0px;
  background-color: #FF0000;
}

3. Programming jQuery functions

Now comes the most exciting and important part of the feature. We first include jQuery before the closing body tag and then the code for the bar.

<script loading="lazy" src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

You can either embed JQuery using the following script tag or download it and embed it locally.

$(function() {
  $(window).scroll(function() {

    var offset = $(window).scrollTop();
    var windowHeight = $(window).height();
    var height = $(document).height();

    var progress = (offset / (height - windowHeight)) * 100;

    $("#read-progress.progress-bar").css("width", progress + "%");
  });
});

And that’s it! Your Reading Position Indicator is ready. You can now insert the code into HTML or PHP according to your page. There are also other features that you can easily create yourself, such as your own WYSIWYG editor with pure JavaScript.

Related Posts
NEW 🚀
Leave a comment

Your email address will not be published. Required fields are marked *