Only run a jQuery animation once, then do other stuff, then reverse the animation
I have a menu with a set of li
's which, when hovered over, animates the height of the container and then shows the related child .subnav
.
The problems I am having are 2fold.
When I hover over the
li
's quickly, the animation of the container slows down as it is starting the animation again from that point. I would like to be able to say "Only animate this once when hovering over anyli
's" and then return it to it's original position when hovering out of the container or subnav.When the
.subnav
content is showing and I hover over another trigger li, the animation seems to be trying to run on the container again and as such means there is a delay in any actions that are supposed to occur after.
I have tried using unbind()
and bind()
but was unsuccessful, I also tried using :animated
but I can't seem to get the logic right.
Here is my code:
var navHeight = $('#primary-nav').height();
$('#prima开发者_如何转开发ry-nav-list li').hover( function() {
var elem = $(this);
if ($(this).is('#roc-noir')){ var subnavHeight = 173; }
else { var subnavHeight = 235; }
$('#primary-nav').stop(true,false).animate({height:subnavHeight}, function(){
$('#primary-nav-list li').removeClass('active');
$(this).addClass('open');
$(elem).addClass('active');
$('#primary-nav-list li').not(this).find('.subnav').fadeOut('fast');
$(elem).find('.subnav').fadeIn('fast');
});
}, function(){
$('#primary-nav').removeClass('open');
$('#primary-nav').stop(true,false).animate({height:navHeight}, function(){
$('#primary-nav-list li').removeClass('active');
$('#primary-nav-list li').not(this).find('.subnav').hide();
});
});
Any help would be appreciated.
Take a look at the Hover Intent plugin and see if it does what you need. It adds a slight delay before starting, and subsequently "stopping" the animation.
Maybe something like this -- a flag for abort if it is already running?
var navHeight = $('#primary-nav').height();
var running = false;
var controller = {
hoverIn : function() {
if (running) return;
running = true;
var elem = $(this);
var subnavHeight = 235;
if ($(this).is('#roc-noir')) { subnavHeight = 173; }
$('#primary-nav').stop(true,false).animate({height:subnavHeight}, function(){
$('#primary-nav-list li').removeClass('active');
$(this).addClass('open');
$(elem).addClass('active');
$('#primary-nav-list li').not(this).find('.subnav').fadeOut('fast');
$(elem).find('.subnav').fadeIn('fast');
});
},
hoverOut : function(){
if (running) return;
$('#primary-nav').removeClass('open');
$('#primary-nav').stop(true,false).animate({height:navHeight}, function(){
$('#primary-nav-list li').removeClass('active');
$('#primary-nav-list li').not(this).find('.subnav').hide();
running = false;
});
}
$('#primary-nav-list li').hover(controller.hoverIn,controller.hoverOut);
精彩评论