Use jquery to create animated progress bars in various designs


I am attempting to create an animation in JavaScript for multiple Bootstrap progress bars, each based on their individual widths. However, I have encountered an issue where the code only takes the value of the first DOM element with the class "progress-bar." Can someone please provide guidance on how to resolve this issue? Thank you in advance :)

Below is my code:

HTML

<h5>Coffee Demand</h5>
  <div class="progress">
    <div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100" style="width:70%">
      70% Complete (danger)
    </div>
  </div>

  <h5>English Language</h5>
  <div class="progress">
    <div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100" style="width:70%">
      C1 Level (danger)
    </div>
  </div>
    <h5>German Language</h5>
  <div class="progress">
    <div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width:60%">
      A2 Level
    </div>
  </div>

JS

$(function () {
var cWidth = $('.progress-bar').css("width")
$(".progress-bar").animate({width: cWidth}, 1500)
});

EDIT I was able to fix the issue by using a modified version of the code provided by @streetlamp.

However, I am still not completely satisfied as there is a slight freeze at the beginning of the animation. Any suggestions on how to make it smoother?

$(".progress-bar").css("width", "0px")
$(function() {
    $(".progress-bar").each(function() {
        var finalWidth = parseInt($(this).attr("aria-valuenow"));
        $(this).css("width", "0px").animate({width: finalWidth+"%"}, 1000);
    });
});

Thank you for all your assistance thus far.

Answer №1

Iterate over the elements using $.each() and apply animation to each element based on its aria-valuenow attribute (please note: this example is for demonstration purposes only, aria-valuenow should reflect the current value):

$(function() {
    $(".progress-bar").each(function() {
        var finalWidth = parseInt($(this).attr("aria-valuenow"));
        $(this).css("width", "0px").animate({width: finalWidth+"%"}, 1500);
    });
});

Answer №2

To target each .progress-bar, use the method eq().

Code:

$(function () {

  var progressBars = $(".progress-bar");

  progressBars.eq(0).animate({width:"50%"}, 1500)

  progressBars.eq(1).animate({width:"70%"}, 1500)

  progressBars.eq(2).animate({width:"85%"}, 1500)

});

The width is set individually in percentages.

In the HTML code, remove the width value and set it to 0 in CSS for proper animation.

Css:

.progress-bar {
  width:0px;
}

Here is an example that works.

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

Issues with HTML2PDF image rendering limitations

I'm encountering an issue where the image tag is not working with the following HTML code being displayed in a PDF: $html.= "<h2>Header</h2>\n"; $html.= "<p>Text</p>\n"; $html.= "<img src=" . $path1 ."> ...

Trouble with selecting inputs within a Div Element

Could you please review the code below and help me understand why I am unable to retrieve the ID of the selected radio buttons using this.id? <div id="pay" class="btn-group" data-toggle="buttons"> <label class="btn btn-primary"> < ...

"During a single click event, the jQuery AJAX function is invoked a total of 6

For my project using C# MVC 5, I have implemented an AJAX call on the client side with the following code snippet: function addEventListener() { $('#createNotification').bind('click', function (e) { if($('# ...

Updating the state in React can be achieved by using the `

Upon obtaining a list of search results, each result is equipped with an onclick function. My goal is to exhibit the user-selected results on the screen by adding them to an array upon click: let selectedData = [] function addFunc(resultdata){ consol ...

Creating or accessing maps using TypeScript and Cloud Functions in Firebase

In my document, there is a map referred to as "map" with a specific structure: -document -map {id: number} {id2: number2} When the function first executes, only the document exists and I need to create the map with an initial entry. Before ...

Dealing with Node.js, MongoDB, ISODate, and the complexities of managing time zones

Hey there, currently I am working with node js + mongodb. One issue I am facing is that whenever I insert data into a collection, it gets stored in the default ISODate format e.g. ISODate("2016-06-17T13:00:21.665Z") I want to make sure that the date fiel ...

Why doesn't the Iframe onLoad event trigger when uploading a file?

I have a straightforward iframe <iframe class="ifr" src="about:blank"></iframe> It contains an onload handler. $(".ifr").on('load',function (){ alert("iframe loaded") }); There are also two buttons: Pressing the first button ...

The layout of a Vuex store in a sprawling website

Currently immersed in the development of a sprawling website using Vue.js, I find myself grappling with the architecture of Vuex store. The current folder structure is as follows: . ├── build ├── src │ └── components │ ├ ...

Attempting to use vue-test-utils-getting-started with the standard configuration results in a "Preset Not Found" error during

Currently, I am in the process of conducting a unit test by referring to the official guide provided. To do so, I have cloned the demonstration repository named vue-test-utils-getting-started. To replicate the issue, follow these steps: After cloning vu ...

Freemarker substitute & and &ampersand;

I am facing an issue with Freemarker. I need to eliminate all the special characters from this sentence as well as from similar sentences in the future: BLA BLA RANDOM &, RANDOM BLA In particular, I want to remove the & character. The platform ...

Achieve a sliding effect between two divs using CSS only

I'm trying to create a design with 2 divs that are the same size. The first one is visible by default, while the second one is hidden initially. My goal is to achieve an effect where when you hover over the first div, the second one slides upward and ...

What causes the delay in monitoring the oplog in Meteor and Mongo?

I recently implemented Oplog tailing in my Meteor.js app using my MongoLab cluster to enhance performance, availability, and redundancy. However, I have noticed that since incorporating this feature, my publications are taking longer to complete. While a d ...

What is the best way to arrange the elements of a dropdown list in reverse order?

I have the following code snippet used to retrieve data from a database and display it in a dropdown list: @{ int m = 1; foreach (var item in Model.MessagesList) { if (@item.receiverUserId == userId) { <li> <a class=&qu ...

Testing jQuery AJAX request with echo on jsFiddle

I'm encountering an issue where the code is displaying 'undefined' instead of appending the response data in HTML format. Can anyone shed some light on what might be causing this? JavaScript: $(function() { $('.document').on ...

Combining Java for the back-end and JavaScript for the front-end: a comprehensive guide

Looking for advice on integrating a Java back-end with a JavaScript, HTML 5 front-end in my web application. Any tips on passing content between the two languages? ...

How can I populate a select dropdown list in Django using JsonResponse?

I've been working on displaying a list from my Django application in an HTML select option, but I'm having trouble getting it to show up. Also, I believe I need to assign IDs to the option values in the select list, but I'm not sure where to ...

What is the best way to implement a shared function across two classes?

I have a jQuery code that works as intended with the .foto class. Now, I need to add the .fotoleft class to perform the same function. How can I make the function work for two different classes? $(document).ready(function() { $(".foto").click(functi ...

Troubleshooting a Dysfunctioning Character Counter Feature in a JavaScript Input Field

I've been working on a fun little project to practice my JavaScript skills - a plate calculator. Here's the gist: you enter your name, and each letter costs $5, so the total cost of the plate is the length of your name multiplied by $5 (this pro ...

Calculate the sum of a specific column in an HTML table using JavaScript after

I have a function called CalColumnHistDEPOSITO() that I use to sum a table column as it loads from the server side into my HTML page. However, when I apply a filter, it continues to sum the entire table ignoring the filter. (function() { 'use stric ...

Storing JSON responses from a web service into a database using Linux wget in the background

I encountered a major issue. I have written a script in jQuery to communicate with a webservice, sending JSON data and receiving JSON responses in return. Here's a snippet of the code: function Product(date_from,date_to,API_KEY) { var self = this; se ...