Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery mouseover mouseout opacity

    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.

like image 806
a-second-mix Avatar asked May 18 '11 10:05

a-second-mix


3 Answers

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.

like image 82
T.J. Crowder Avatar answered Nov 08 '22 00:11

T.J. Crowder


You need to add a call to .stop() before you animate to clear the current and any queued animations:

function hoverOpacity() {
    $('#fruit').mouseover(function() {
        $(this).stop(true).animate({opacity: 0.5}, 1500);
      });
    $('#fruit').mouseout(function() {
        $(this).stop(true).animate({opacity: 1}, 1500);
      });
}
like image 23
Rory McCrossan Avatar answered Nov 08 '22 00:11

Rory McCrossan


Try this:

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

This should stop the animation, clear the queue (first arg) and jump to the end (second arg), you can change / mess around with the arguments as appropriate.

like image 1
Ben Everard Avatar answered Nov 08 '22 02:11

Ben Everard