Programming Reading Position Indicator with jQuery

Programming Reading Position Indicator with jQuery

Reading Position Indicator
Example

Reading progress indicator, scroll position or scroll indicator: The mysterious bar has many names, but the best known is probably Reading Position Indicator. Such a bar can also be found in the header of this post. Here you can learn how to program this feature with jQuery and CSS.

1. Prepare HTML structure

First we need the actual ledge. 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 can look like this:

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

2. Styling with CSS

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

If you would like to write the CSS yourself, you can use this structure as a basic framework and, for example, still adjust colors and strength:

.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. First we 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.4.0/jquery.min.js"></script>

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

The following function is deliberately programmed without ES6 features, as some browsers still do not support many new features.

$(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.

Leave a comment

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