Reputation: 1643
We are using the following to animate a div on hover and then animate back to its original state on mouseout.
Everything works fine, however the mouseout does not fire until we have hovered over the div a 2nd time. After that, it works perfectly.
$('#navigation-captions>li>a')
.hover(function(){
if(!$(this).next().is(".open")) {
$(this).next().css({'visibility' : 'visible'}).animate({opacity: 1}, 150).addClass('open')
}else if ($(this).next().is(".open")) {
$('#navigation-captions>li>a').mouseout(function(){
$(this).next().stop().animate({opacity: 0}, 150, function(){$(this).next().css({'visibility' : 'hidden'})}).removeClass('open')
})}})
Thanks in advance for any help!
Upvotes: 1
Views: 202
Reputation: 3715
Would this work for your situation?
$('#navigation-captions>li>a').hover(function() {
$(this).next().css({'visibility' : 'visible'}).stop().animate({opacity: 1}, 150).addClass('open');
}).mouseout(function() {
$(this).next().stop().animate({opacity: 0}, 150, function(){
$(this).next().css({'visibility' : 'hidden'}).removeClass('open')
})
});
The event will always work the first time. Removing the if-block, makes the code cleaner and makes it less likely to get into an inconsistent state.
Also, it is recommended you use on() if your version of jQ supports it.
$('#navigation-captions>li>a').on('hover', function() {
$(this).next().css({'visibility' : 'visible'}).stop().animate({opacity: 1}, 150).addClass('open');
}).on('mouseout', function() {
$(this).next().stop().animate({opacity: 0}, 150, function(){
$(this).next().css({'visibility' : 'hidden'}).removeClass('open')
})
});
Upvotes: 1