jQuery Progress Bar: animate-reset-animate

1.4k Views Asked by At

I have a progressbar which is being animated in a mouseover event in the following way:

$("#progressbar .ui-progressbar-value").animate({width: 200}, {duration: 3000},'slow')

Then in a mouseout event I want to reset the progressbar to its initial state and then if mouseover is called again the animation must start again.

I've got to the point where I am able to reset the value like this:

('#progressbar').progressbar({value: 0});

But from there on another mouseover does not start the animation again. I thought the problem might be because before the first animation the value is initialized to 1. However, setting it to 1 does not reset the animation at all. Lastly I tried to first reset it to 0 and then set it to 1 as in the initial state without success.

FIDDLE

1

There are 1 best solutions below

2
ılǝ On BEST ANSWER

The first part of your logic is wrong. .progressbar resets the progressbar to its original state, which is correct. However, with .animate you're merely changing the css, you're not actually 'progressing' the bar.

You should be setting a value over some computation/ period of time, while mouse is over the element instead.

Example (edited):

html

<div id="progressbar"></div>

js

$(function () {
    var progress = 0;
    var updateTime = 30; // ms
    var updateTimeout;

    $("#progressbar").mouseenter(function () {
        updateTimeout = setTimeout(animateFilling, updateTime);
    });

    $("#progressbar").mouseleave(function () {
        progress = 0;
        updateProgressbar();
        clearTimeout(updateTimeout);
    });

    updateProgressbar(); // init the bar

    function animateFilling() {
        if (progress < 100) {
            progress++;
            updateProgressbar();
            updateTimeout = setTimeout(animateFilling, updateTime);
        } else {
            // TODO - done loading
        }
    }

    function updateProgressbar() {
        $("#progressbar").progressbar({
            value: progress
        });
    }
});

Updated demo here

Mouseover / mouseout bug edit

As noted by the OP, using mouseover and mouseout would retrigger the progress bar even despite the cursor hasn't left the dom element (resulting either in speeding up or resetting the progress bar).

This is due to the progress bar's inner element and to event bubbling, as described here. We can avoid this by using mouseover / mouseout instead.