Reputation: 797
I try to write js to animate several bootstrap progress bar based on thier width. I write simple code but its not working, probably because its takes value of first DOM element with class progress bar. Can you please suggest me how can i resolve this issue ? Thank you very much :)
Here is my code:
HTML
<h5>Zapotrzebowanie na kawę</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>J. Angielski</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 (danger)
</div>
</div>
<h5>j. Niemiecki</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
</div>
</div>
JS
$(function () {
var cWidth = $('.progress-bar').css("width")
$(".progress-bar").animate({width: cWidth}, 1500)
});
EDIT So i manage to resolve problem by using modified code provided my @streetlamp
Yet im not quite satisfied with it, cause it a little freeze at the bening. Not smooth enough. Do you have some suggestion ?
$(".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 help so far .
Upvotes: 1
Views: 2260
Reputation: 2207
We can target each .progress-bar
by eq()
Code:
$(function () {
var prog = $(".progress-bar");
prog.eq(0).animate({width:"50%"}, 1500)
prog.eq(1).animate({width:"70%"}, 1500)
prog.eq(2).animate({width:"85%"}, 1500)
});
We set the width in percentages individualy.
At the html code remove the width
value we will set it in css to 0 so we can animate it properly.
Css:
.progress-bar {
width:0px;
}
here is the working example.
Upvotes: 0
Reputation: 1556
Loop through the elements using $.each()
and animate each to the value of the element's aria-valuenow
parameter (don't actually do this in production, aria-valuenow
is supposed to be the value now):
$(function() {
$(".progress-bar").each(function() {
var finalWidth = parseInt($(this).attr("aria-valuenow"));
$(this).css("width", "0px").animate({width: finalWidth+"%"}, 1500);
});
});
Upvotes: 2