0

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

Konstantin
  • 396
  • 3
  • 19

1 Answers1

2

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.

Community
  • 1
  • 1
ılǝ
  • 3,440
  • 2
  • 33
  • 47
  • 1
    Thanks a lot. Just one more question. I've modified it so that it starts always from 0. But there is this problem that even if you keep your mouse in the border of the pb and you move it around the mouseout event is triggered. I tried adding container around the pb and connecting the events to it without success: https://jsfiddle.net/ConstantinV/5ppL7144/6/ – Konstantin May 19 '15 at 17:33
  • You're right, the progress var should be cleared - I'll edit and comment on the mouseout bug. – ılǝ May 20 '15 at 06:12