jQuery mouseover mouseout opacity

a-second-mix picture a-second-mix · May 18, 2011 · Viewed 8.1k times · Source
    function hoverOpacity() {
    $('#fruit').mouseover(function() {
        $(this).animate({opacity: 0.5}, 1500);
      });
    $('#fruit').mouseout(function() {
        $(this).animate({opacity: 1}, 1500);
      });
}

This is my function that animates div#fruit, and it does it work.

The problem is this; When you mouseout before the mousein animation finishes, it has to complete the animation before starting the mouseout. (hope that makes sense)

This isn't usually noticeable, but with a long duration, it is noticeable.

Instead of finishing the animation, I want the animation to stop and reverse to the original state.

Answer

T.J. Crowder picture T.J. Crowder · May 18, 2011

You're looking for the stop function, possibly followed by show (or hide, or css, depends what state you want opacity to end up in).

function hoverOpacity() {
    $('#fruit').mouseover(function() {
        $(this).stop(true).animate({opacity: 0.5}, 1500);
      });
    $('#fruit').mouseout(function() {
        $(this).stop(true).animate({opacity: 1}, 1500);
      });
}

The true tells the animation to jump to the end. If this is the only animation on the element, it should be fine; otherwise, as I said, you could look at css to explicitly set the desired opacity.

Separately, though, you might look at using mouseenter and mouseleave rather than mouseover and mouseout, for two reasons: 1. mouseover repeats as the mouse moves across the element, and 2. Both mouseover and mouseout bubble, and so if your "fruit" element has child elements, you'll receive events from them as well, which tends to destabilize this kind of animation.