-3

Here's the page in question: http://yac-web.com/clients/dessert/ I am trying to set up an effect that happens while the mouse is being moved and stops when it's not. For some reason the event starts fine but then just keeps looping. I am not super familiar with JS and couldn't find much info on the mousemove event. Thanks

$('html').mousemove(function () {
    $('html').toggleClass("change", 1000, "easeOutSine");
})

then

html {
    background: rgba(191, 54, 245, 1);
}
.change {
    background: rgba(61, 98, 245, 1);
}

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531

2 Answers2

4

The basic problem is when the mouse is moved you are queuing a lot of toggle classes which uses a queuing system so even after the mouse is stopped the animation will continue to run.

The solution is not to add more toggles if there is a animation in progress, try

var flag = false;
$('html').mousemove(function () {
    if (flag) {
        return;
    }
    flag = true;
    $('html').toggleClass("change1", 1000, "easeOutSine", function () {
        flag = false;
    });
})

Demo: Fiddle

Another is to use :animated selector

var $html = $('html').mousemove(function () {
    if ($html.is(':animated')) {
        return;
    }
    $('html').toggleClass("change1", 1000, "easeOutSine");
})

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Thanks this was pretty helpful, now would there be a way to do this where the transition would actually pause or stop when the mouse stops moving rather than finishing the current transition in queue? – A BOY n HIS PIG Nov 15 '13 at 15:34
  • Actually in both those demos the effect is continuing to loop. Maybe toggleClass isn't the best way to do this? or is the problem caused by the way mousemove works? – A BOY n HIS PIG Nov 15 '13 at 15:51
0

Arun P Johny's answer is probably the best in terms of actually solving the problem, however it doesn't go into depth as to exactly why it is happening.

This is why the problem is happening:

Each time the mouse position updates (several times a second, unless you are having serious lag; I will assume 1/16th of a second between updates), it adds a new animation to the end of the list of animations it needs to do. Then, when you stop moving your mouse, it still has a number of the animations left in the queue, which take an entire second each. It is adding a second on to the animation time every 1/16 of a second that you are moving the mouse. Thus, if you move it for one second, it will be 16 seconds after you started that the animation will stop.

This is solved by ensuring that a new animation is not added until the old one finishes.

AJMansfield
  • 4,039
  • 3
  • 29
  • 50