mrpinkman
mrpinkman

Reputation: 211

Avoid jQuery code repeat

i am making an animated progress bar. It's code is quite simple but the problem is that I can't figure out how to avoid repeating some jQuery code, you can see it in this Fiddle:

http://jsfiddle.net/N6c2q/

basically, this is what repeats:

$('.bar-value').animate({width: '+=1%'},50,function(){
    var percent = $('.bar-value').width() / $('.bar-value').parent().width()*100;
    var percInt = parseInt(percent);
    $('.progress').text(percInt+"%");
});

that just increases the width of the inner div (progress) by 1%, and increases .progress span number by 1. Is there any way to do what i'm trying to do without repeating that code?

Thanks in advance!

Upvotes: 1

Views: 169

Answers (3)

db306
db306

Reputation: 1010

Of course, that code is madness!!

So I would recommend you to use jQuery UI progress bar

Otherwise you can use a loop to do what you are trying to achieve:

http://jsfiddle.net/db306/N6c2q/3/

$(document).ready(function(){
    var percent = $('.bar-value').width() / $('.bar-value').parent().width()*100;
    $('.progress').text(percent+"%");

    $('button').click(function(){
        $('.loader').fadeIn(1200);
        $('button').attr('disabled','disabled');


        for (var i=0; i<100;i++){
            $('.bar-value').animate({width: '+=1%'},50,function(){
            var percent = $('.bar-value').width() / $('.bar-value').parent().width()*100;
            var percInt = parseInt(percent);
            $('.progress').text(percInt+"%");
        });
        }
    });
});

Upvotes: 0

Jefraim
Jefraim

Reputation: 193

Use recursion:

function showProgress(finish) {
    $('.bar-value').animate({
        width: '+=1%'
    }, 50, function () {
        var percent = $('.bar-value').width() / $('.bar-value').parent().width() * 100;
        var percInt = parseInt(percent);
        $('.progress').text(percInt + "%");

        if (percInt != 100) {
            showProgress(finish);
        } else {
            if (finish) finish();
        }
    });
}

Fiddle

Edit: fix

Upvotes: 1

Darius Houle
Darius Houle

Reputation: 465

Just give duration and amount you'd like to animate:

$('.bar-value').animate({width: '+=100%'},2000,function(){
    var percent = $('.bar-value').width() / $('.bar-value').parent().width()*100;
    var percInt = parseInt(percent);
    $('.progress').text(percInt+"%");
});

Upvotes: 6

Related Questions