Jquery is not displaying the background color of the progress bar

Greetings to all! I am currently working on implementing a progress bar for my website, but I am encountering an issue where the background-color is not displaying correctly on scroll. I would greatly appreciate any assistance with this matter. Below you can find the code snippets for html, css, and jquery...

HTML Code

<div class="progress-bar-container"><div id="progressbar" value="0"></div></div>

CSS Code

    height: 5px;
    background-color: #ced4da;
    overflow: hidden;
    width: 100%;
    position: sticky;
    position: -webkit-sticky;
    top: 48px;
    z-index: 440;
}
.progress-bar-container #progressbar {
    background-color: #4688f1;
    height: 100%;
    width: 0;
}

jQuery Code

      $(window).scroll(function () {
          var s = $(document).scrollTop(),
              d = $(document).height() - $(window).height();
          $("#progressbar").attr('max', d);
          $("#progressbar").attr('value', s);
       });
   });

If anyone could provide guidance on how to ensure the background color displays correctly on scroll, it would be highly appreciated. Thank you in advance!

Answer №1

Your code has a few issues to address. Firstly, the HTML width attribute does not support the div element. Additionally, the value attribute is also not supported by the div. To create a progress bar, it is recommended to use CSS. Instead of updating the value with

$("#progressbar").attr('value', s);
, you should update the width of the element with $("#progressbar").width(s);

Below is an example of how this can be achieved:

$(window).scroll(function () {
    var s = $(document).scrollTop(),
        d = $(document).height() - $(window).height();
    $("#progressbar").width(s);
});
body {
    background: #20262E;
    padding: 20px;
    font-family: Helvetica;
}
.progress-bar-container{
    height: 5px;
    background-color: #ced4da;
    overflow: hidden;
    width: 100%;
    position: sticky;
    position: -webkit-sticky;
    top: 48px;
    z-index: 440;
}
.progress-bar-container #progressbar {
    background-color: #4688f1;
    height: 100%;
    width: 0;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="progress-bar-container"><div id="progressbar"></div></div>
<div style="height: 120vh"></div>

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

</body>
</html>

Answer №2

To create a progress bar that reflects the percentage, you need to calculate the width and set it accordingly. See the code snippet below for details.

$(window).scroll(function () {
  var  d = $(document).height() - $(window).height(),
       s = $(document).scrollTop(); 
  var  width= (s / d) * 100 // in Percentage
  $("#progressbar").attr('max', d);
  $("#progressbar").attr('value',s).css("width",width +"%");
});
body{
height: 1000px;
}

.progress-bar-container{ 
    height: 5px;
    background-color: #ced4da;
    overflow: hidden;
    width: 100%;
    position: sticky;
    position: -webkit-sticky;
    top: 48px;
    z-index: 440;
}
.progress-bar-container #progressbar {
    background-color: #4688f1;
    height: 100%;
    width: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="progress-bar-container">
<div id="progressbar" value="0"></div>
</div>

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

Attempt to efficiently register components automatically on a global scale in Vue by utilizing the powerful combination of Laravel-Mix and Webpack

In my previous projects with Vue, which were based in a Laravel-Mix/Webpack runtime environment, I used to individually register components and views as needed. This was done by importing them and extending Vue: import BaseButton from './components/Ba ...

Include the providers after declaring the AppModule

When it comes to Angular 2+, providers are typically registered in the following manner: // Using the @NgModule decorator and its metadata @NgModule({ declarations: [...], imports: [...], providers: [<PROVIDERS GO HERE>], bootstrap: [...] }) ...

Interpreting an undefined HTTP GET request within a Node.js server

I am encountering an issue within my Node.js application. When I send an http get request through an ajax call on the client-side, the server-side does not recognize the request data and returns an "undefined" error message. This problem is puzzling to me ...

js/jquery Asynchronous Loading of Content Replaces Existing Page Content

I have encountered a problem that I am hoping someone can assist me with. Here is the issue: A partner of mine has given me a code to use on my website, which will display certain content that I am interested in. However, this content is only relevant to ...

Could implementing a click/keydown listener on each cell in a large React datagrid with thousands of cells impact performance?

Years ago, before the advent of React, I mastered linking events to tables by attaching the listener to the <tbody> and extracting the true source of the event from the event target. This method allowed for a single listener for the entire table, as ...

Is it possible to efficiently update the innerHTML of multiple div elements using a single function?

Upon clicking a button, I am dynamically updating the content of multiple divs using innerHTML. Currently, the button triggers a new video source to load, but I also want to change other types of content in different divs at the same time. I wonder if cha ...

The second guard in Angular 5 (also known as Angular 2+) does not pause to allow the first guard to complete an HTTP request

In my application, I have implemented two guards - AuthGuard for logged in users and AdminGuard for admins. The issue arises when trying to access a route that requires both guards. The problem is that the AdminGuard does not wait for the AuthGuard to fini ...

retrieving the value of an object key based on changing information

console.log(x, obj.fares) //return undefined output adultFare Object {adultFare: "9.00", childFare: null, seniorCitizenFare: null, disabledFare: null,} How do I retrieve the adultFare value from the object? Is looping through the keys necessary? I expec ...

Issues with jQuery .submit() function not functioning properly following an ajax request

I am having an issue where I want to automatically submit a form if a certain condition is true, but for some reason it's not working as expected. I have tried debugging with firebug, but the form isn't getting submitted and I can't figure o ...

Discover how to use jQuery to add CSS styles to every span element on a

I'm currently using JavaScript and jQuery to create a tree structure in ASP.NET MVC. There's an 'add' button that will add siblings and child nodes at the same level. To determine the appropriate action, I have implemented the followi ...

Troubleshooting permission problems with Yarn and node_modules in a Docker environment

I have a Docker container containing a Symfony 6 web application and various other services like php-fpm, node, and python. Additionally, I have separate containers for MySQL and Nginx, all running on Alpine 3.15. My current issue arises when I execute do ...

Returning to the previous page

Having some trouble navigating back to the previous page. When I click the cancel button, it runs a function that uses history.back();, which works correctly. However, there is a validation on the page, so it checks all fields before navigating back. I&ap ...

Tips for substituting commas and slashes within an input text box

For instance, if the input is "1,23/456", the output should be "123456". When "1,23/456" is entered into the input field and "enter" is pressed, it should automatically convert to "123456". <input id="Id" ng-model="Id" name="searchInput" type="text"&g ...

Streaming the request body in NodeJS using ExpressJS without buffering

Looking for a solution to process requests with no specified content-type as binary files. const app = express(); app.use(bodyParser.raw({type: (req) => !req.headers['content-type'], limit: '500mb' })); Some of these files can be ...

Color schemes for items in the Windows store app

I'm having trouble changing the background color of an item in my split application. I've tried using CSS, but nothing seems to work. Here is the template for the item (default style): <div class="itemtemplate" data-win-control="WinJS.Bindin ...

Encountered a buildkite error stating that the plugins file is either missing or invalid, resulting in a failure to locate the module 'xlsx' when executing a cypress test. Strangely

Encountering an issue while running my Cypress test on Buildkite. Here's the error message: Status: Downloaded newer image for cypress/included:6.1.0 [2022-01-31T10:32:13Z] Your pluginsFile is set to /e2e/cypress/plugins/index.js, but either the fil ...

Rotate through different image sources using jQuery in a circular pattern

I'm working on a project where I have 3 img tags in my HTML file. My goal is to change the src of all 3 images with a button click, using an array that stores 9 different image src links. When the page initially loads, it should display the first set ...

Utilize JSON data from a service to populate a Bootstrap Modal

I need assistance with populating a Modal using the JSON values I received from a service call. The object structure is simple and understandable, like this: var object = [ {Value1: "Val1", Value2: "Val", Value3: [{a:"a",b:"b"}] }] The ajax call looks ...

Move a sub-division horizontally within a parent element that has a full width of 100%

I am currently incorporating some jQuery features into my website. The concept involves expanding the parent div to 100% width for responsive design as you scroll down the page, which works perfectly. Simultaneously, I aim to translateX the child div so th ...

Should the button be eliminated in favor of simply requesting input from the user?

Looking for help with my code. How can I set it up so that when the HTML file is clicked on, it prompts for input instead of displaying a button? I'm new to coding and could use some guidance. <!doctype html> <html> <head> <meta ...