Zach
Zach

Reputation: 5073

How to have multiple dynamic jQuery progress bars

I am trying to have multiple progress bars animate at the same time, but to different values. Using the following HTML and jQuery both bars go to the same end value.

<progress id="progressbar" value="50" max="100"></progress><span class="progress-value">0%</span>
<progress id="progressbar" value="30" max="100"></progress><span class="progress-value">0%</span>

......

<script>
$(document).ready(function() {

var progressbar = $('#progressbar'),  
        max = progressbar.attr('value'),  
        time = (1000/max)*2,      
        value = 0 

    var loading = function() {  
        value += 1;  
        addValue = progressbar.val(value);  

        $('.progress-value').html(value + '%');  

        if (value == max) {  
            clearInterval(animate);                      
        }  
    };  

    var animate = setInterval(function() {  
        loading();  
    }, time);  

});
</script>

I know that this is because both instances of the progressbar are just following the same jQuery, but I have no idea how to make it dynamic. Any help would be appreciated.

EDIT:

var progressbar2 = $('#progressbar2'),  
max2 = progressbar2.attr('value'),  
time2 = (1000/max2)*2,      
    value2 = 0 

    var loading2 = function() {  
    value2 += 1;  
    addValue = progressbar2.val(value); 

    $('.progress-value2').html(value + '%');  

    if (value2 == max2) {  
        clearInterval(animate2);                      
    }  
}; 
var animate2 = setInterval(function() {  
    loading2();  
}, time);  

This works (adding a clone of the original function), but obviously it's not something I want to do. Is there a way I could iterate through all of the possible progress bars I'll have, using something similar to a for loop?

Upvotes: 3

Views: 1773

Answers (1)

omer schleifer
omer schleifer

Reputation: 3935

You should give each control a different id , e.g. progressbar1 , progressbar2 etc.. You can use class selector instead of id selector, then iterate over each element with the "progress-value" class. like so:

$('.progress-value').each(function(i, obj) {
    //your code here
});

Upvotes: 3

Related Questions