Zaemz Zaemz - 6 months ago 17
Javascript Question

jQuery-ui stop() animation causing styles to stick

I have an unordered list with divs in it. When one is hovered over, the others have a class applied to them that makes them fade out, slightly.

<ul class="three_up tiles">
<li id="ember283" class="ember-view questioncontainer"></li>
<li id="ember293" class="ember-view questioncontainer"></li>
<li id="ember298" class="ember-view questioncontainer"></li>
<li id="ember299" class="ember-view questioncontainer"></li>
<li id="ember300" class="ember-view questioncontainer"></li>
<li id="ember301" class="ember-view questioncontainer"></li>
<li id="ember302" class="ember-view questioncontainer"></li>
</ul>


The issue that's occurring is that when a user quickly navigates over them, some will stick with their styling at a certain point.

There's a fiddle here: http://jsfiddle.net/QusWU/1/

What should my solution be?

Answer

The problem is that when you use the version of .addClass that animates, it does not add the class to the element until the animation finishes. And if the class is not added, then the call to removeClass does nothing.

As @ArunPJohny points out, you can use .stop(true, true) to jump the animation to the end so the class will get added. That has its own problem though because you don't want the visual effect.

Perhaps you should not use a class and just animate the opacity. That way, it is fine for the animation to stop in the middle and reverse.

var $containers = $(".questioncontainer");

$containers.mouseenter(function () {
    var $container = $(this);
    $container.stop().animate({ opacity: 1.0 }, 500);
    $container.siblings().stop().animate({ opacity: 0.2 }, 500);
});

$containers.mouseleave(function () {
    $containers.stop().animate({ opacity: 1.0 }, 500);
});

jsfiddle