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.
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.
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);
});
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With