Lindsay Roberts
Lindsay Roberts

Reputation: 35

Animate HTML5 Progress Bar with JavaScript

I'm trying to do a simple HTML5 progress bar. When a user clicks a button, I want it to (onclick) begin the animation so that it goes from 0-100 (full) in three seconds. It should be some really basic Javascript that I'm looking to throw in the head of my document.

Very similar to this: HTML5 progress bar animation

I just need it onclick instead of onload and with a button. It's just a standard HTML progress bar, so it looks like this:

<progress id="progress" value="0" min="0" max="100">0%</progress>
<input type="button" value="button" onclick="[make_progress_bar_go_from_0_to_100]">

Upvotes: 2

Views: 9698

Answers (1)

Ezequiel Muns
Ezequiel Muns

Reputation: 7742

All you need is this example from the question you posted: http://jsfiddle.net/526hM/

The part that attaches it to the onload is this:

$(document).ready(function(){
    ...
    setTimeout(animator, updatesPerSecond);
}

All you need to do is attach this animator function to a button instead. To get the effect to happen in 3 seconds, update the timing variables.

HTML:

<progress max="200" value="0"></progress>
<button id="theButton">Start!</button>

Script:

$(document).ready(function(){
    var msecsPerUpdate = 1000/60; // # of milliseconds between updates, this gives 60fps
    var progress =  $('progress');
    var duration = 3;             // secs to animate for
    var interval = progress.attr('max')/(duration*1000/msecsPerUpdate);

    var animator = function(){
            progress.val(progress.val() + interval);
            if (progress.val() + interval < progress.attr('max')){
               setTimeout(animator, msecsPerUpdate);
            } else {
                progress.val(progress.attr('max'));
            }
        }

    $('#theButton').click(function(e) {
        e.preventDefault();
        animator();
    });
});​

Demo: http://jsfiddle.net/526hM/28/

Upvotes: 1

Related Questions