jquery animate on hover with multiple list-items
OK, I've got my desired animation to be very close to what I want; however I'm running into a bug. http://garibaldi.juggernautwebdesign.com/ and it's the #menu-left nav (colourful one). If you hover, it expands open like it's supposed to. And if you let it fully animate, then hover over a new element OR hover off that list-item, it then closes, properly and a new item will open (if you hover over a new list-item). However, if you hover over a list-item and then quickly hover off before it has time to fully animate, then it slides back down too far. Is there any way to stop any animations from happening, until the initial hover is fully animated? I tried using the queue option, but that just stopped any animation on a hover out.
Here's my code:
$(document).ready(function() {
//Left nav
$('#menu-left').children().addClass('closed');
$('#menu-left > li a').click(function(e){
e.preventDefault();
});
$('.closed').live('hover', function() {
var position_open = parseInt($(this).css('bottom')) + parseInt($('.sub-menu', this).css('height')) - 12;
$(this).animate({ bottom: position_open }, function() {
$(this).removeClass('closed');
$(this).addClass('opened');
});
});
$('.opened').live('hover', function() {
var position_close = parseInt($(this).css('bottom')) - parseInt($('.sub-menu', this).css('height')) + 12;
$(this).animate({ bottom: position_close }, function() {
$(this).removeClass('opened');
$开发者_如何学C(this).addClass('closed');
});
});
});
Any help would be greatly appreciated!
You can try adding a flag before calling animate. Something like this:
$(document).ready(function() {
var animating = false;
//Left nav
$('#menu-left').children().addClass('closed');
$('#menu-left > li a').click(function(e){
e.preventDefault();
});
$('.closed').live('hover', function() {
var position_open = parseInt($(this).css('bottom')) + parseInt($('.sub-menu', this).css('height')) - 12;
if(!animating) {
animating = true;
$(this).animate({ bottom: position_open }, function() {
$(this).removeClass('closed');
$(this).addClass('opened');
animating = false;
});
}
});
});
Also, try removing one of the hover handler code. Seems they are stepping over each other.
I can't be sure without more testing, but I'm betting your events aren't bubbling the way you'd expect. You're adding/removing the class while you're still hovering/animating, so the process fires a few times.
I would suggest rewriting the function to trigger off of mouseenter/mouseleave events, I think this would help you making sure the events only fire once. You may not even have to add/remove classes with this method..
$(".slide_box").live('mouseenter', function () {
//animate up
})
$(".slide_box").live('mouseleave', function () {
//animate down
})
精彩评论