a-second-mix
a-second-mix

Reputation: 372

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.

Upvotes: 5

Views: 8201

Answers (4)

T.J. Crowder
T.J. Crowder

Reputation: 1075885

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.

Upvotes: 6

metaforce
metaforce

Reputation: 1377

try this aswell:

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

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337733

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);
      });
}

Upvotes: 2

Ben Everard
Ben Everard

Reputation: 13804

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.

Upvotes: 1

Related Questions