Creating a dynamic progress bar that scrolls for multiple elements

I am currently working on implementing a scrolling progress bar to show users how much of an article within a div they have read.

For reference, something similar can be seen on this site.

I have created my custom progress bar and coded it on fiddle, where you can see it in action.

Here is the code:

HTML:

<br /><br /><br /><br /><br /><br /><br /><br /><br />
<div id="xyz">
    Hello !!<br />
    XYZ<br />
    Hello !!<br />
    XYZ<br />
    Hello !!<br />
    XYZ<br />
    Hello !!<br />
    XYZ<br />
    Hello !!<br />
    XYZ<br />
    Hello !!<br />
    XYZ<br />
    Hello !!<br />
    XYZ<br />
    Hello !!<br />
    XYZ<br />
</div>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<div id="xyzprog"><div id="prog">Intro</div></div>

JQuery/JS:

$(function(){
    $(window).scroll(function(){
    var elemTop=$("#xyz").offset().top,elemHeight=$("#xyz").height();
        var total=elemTop+elemHeight;
        var scTop=$(window).scrollTop();
            var prog=((scTop-elemTop)/elemHeight)*100;
        var html="Intro;Read=";
            if(prog>100){ prog=100; html="Intro;Read=" }
        if(prog<0){ prog=0; }
            $("#prog").animate({
                "width":""+prog+"%"
            },1).html(html+""+prog+"%");

    });
});

CSS is not included as it is irrelevant for this example.

My next step is to:

  • Figure out a way to make this code work for more than one element (at least 10).

  • Create a plugin similar to $(elem).scrollProgress(). Any guidance on how to start would be appreciated.

  • Explore if there are better alternatives to achieve the same functionality.

Any suggestions, ideas, or thoughts on this matter are welcomed!

Thank you in advance :).

Answer №1

If you're looking for a way to track progress while scrolling, there are some existing plugins that can help you achieve this. Take a look at plugin1.

However, if you want to implement this feature across the entire page, you can try the following approach:

$(window).scroll(function() {

  var docHeight = $(document).height();
  var winHeight   = $(window).height();
  var scrollDistance  = $(window).scrollTop();

  var scrolledPercent = scrollDistance/(docHeight - winHeight) * 100;
  $('#progress-indicator').css({'width': scrolledPercent + '%'});
});

I have also created a working demo on jsfiddle which you can view here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to prevent SignalR from disconnecting when the settings window is moved?

I am currently developing a webpage that utilizes SignalR events to trigger ajax requests to our servers. These requests return a URL with a custom URI scheme that, when accessed, opens up a specific program on the client's device without leaving the ...

New approach: AngularJS - Using nested ng-click events

Looking for a solution to a problem with my html code: <div class="outerdiv" data-ng-click="resetText()"> <div class="innerdiv" data-ng-click="showText()"> {{ text }} </div> </div> The outer div has an ng-click fun ...

Attempting to access a variable without wrapping it in a setTimeout function will

I have a form without any input and my goal is to automatically set the "responsible clerk" field to the currently logged-in user when the component mounts. Here's what I have: <b-form-select v-model="form.responsible_clerk" :op ...

Ensure that 8 items out of the total of 12 are displayed within the viewport, with the remaining 4 items

I'm facing a challenge with my HTML layout that looks like this: <div class="container1"> <div class="item">Item 1</div> <div class="item">Item 2</div> ... etc </div> What I want to achieve is having a ...

Placing an image at the forefront of all elements

Recently, I created a horizontal opt-in bar for my Newsletter on my website. Instead of the traditional submit button, I decided to use an image by incorporating some CSS: #mc_embed_signup input.button { background: url(http://urltotheimg.com/image.jpg); ...

Troubleshooting the non-functional asynchronous function

After starting to use redis with node (specifically the node_redis module), I decided to wrap my retrieval code for debugging and DRY principles. However, I encountered an issue where my new function wasn't working as expected. As someone who is stil ...

Ways to display the chosen value based on the item's index using Javascript in Angular

If you want to view the complete code, just click on this link. I have identified the main issue here. Check out the code here: https://stackblitz.com/edit/test-trainin-2?file=src/app/app.component.html The problem is when you interact with the green bal ...

"Utilizing node.js to create a custom regular expression for removing anchor tags

Can someone provide me with a regex pattern that can eliminate all the a tags from HTML and display the URL as plain text? For instance, take this text: abc <a href="http://a.com" target="_blank">bbb</a> ccccccc After applying the regex patt ...

I am currently facing an issue with validating forms in JavaScript Document Object Model (DOM)

Whenever I click on a field and move to another one, the span tag turns red. Then, after pressing the submit button, an alert message pops up. However, if I turn the span red, fill in the field, and press the submit button, it shows success even if other f ...

Execute angular function as you scroll upwards in a chat application with pagination feature

I'm currently working on a chat application and looking to implement pagination upon scrolling up (not down). I am in need of a directive for this task. Additionally, I would like to display a preloader while loading new page data. Can someone advise ...

Can we rely on JavaScript to maintain the order of object properties?

Let's say I define an object in the following way: var obj = {}; obj.prop1 = "Foo"; obj.prop2 = "Bar"; Is it guaranteed that the object will always appear exactly like this? { prop1 : "Foo", prop2 : "Bar" } In other words, will the properties reta ...

How can I write an if-else statement in JavaScript with Mongoose for MongoDB?

I am facing a challenge where I need to execute a statement only if the object is not null. If the object is null, I should skip executing anything. Is there a correct way to achieve this? I attempted it on MongoDB Playground but unfortunately, it did not ...

Send back alternate HTML content if the request is not made via AJAX

Last time I asked this question, I received several negative responses. This time, I will try to be more clear. Here is the structure of a website: Mainpage (Containing all resources and scripts) All Other pages (HTML only consists of elements of that ...

Create a discord.js bot that can randomly select and send a picture from a collection of images stored on my computer

I'm currently working on a bot that sends random pictures from an array of images stored on my computer. However, I encountered an issue when trying to embed the image, resulting in the following error message: C:\Users\47920\Desktop&bs ...

An error occurs when attempting to assign a value to a MUI file TextField

Struggling with setting the value of a MUI Textfield that has type="file" props, resulting in the following exception being thrown: Uncaught DOMException: An attempt was made to use an object that is not, or is no longer, usable Interest ...

Trouble with retrieving JSON data?

Struggling to access the JSON object issue: Received JSON Object: {"71":"Heart XXX","76":"No Heart YYYY"} I attempted to retrieve values for 71 and 72 individually but encountered compile time problems as: Syntax error on token ".71", delete this token ...

Tips for showcasing unique keywords in Ace Editor within the Angular framework

Can anyone help me with highlighting specific keywords in Angular using ace-builds? I've tried but can't seem to get it right. Here's the code snippet from my component: Check out the code on Stackblitz import { AfterViewInit, Component, ...

Vue: add a CSS class to products when they are in the shopping cart

As I delve into creating a shopping cart using laravel + vue, I am encountering a major obstacle related to vue's functionality. Within my cart component, the goal is to allow users to effortlessly add or remove products by simply clicking. When a pr ...

Error: Unable to simplify version range

Attempting to follow the Express beginner's guide. I created an app and executed npm install as per the provided instructions. > npx express-generator --view=pug myapp > npm install npm ERR! semver.simplifyRange is not a function npm ERR! A com ...

Dealing with ng-repeat and button alignment across Chrome, Edge, and Firefox

Can someone help me understand this strange behavior I am experiencing across all browsers? <div style="margin-top:5px"> <button translate="clear" ng-click="xyz.clear()" class="btn btn-default"></button> <butt ...