jquery dropdown div not quite working
i'm trying to make a div drop down when someone hovers over a link. Inside the div is a login form. The following code works only in that if i hover over the link the div does appear. However when i move the mouse from the link down over the div, the div immediately retracts. Please see:
jQuery(document).ready(function() { jQuery('.slidedown'开发者_StackOverflow中文版).hide(); jQuery('a.top-link-cart').hover( function(){ // enter animation jQuery('.slidedown').stop(true,true).animate({ height: ['toggle', 'swing'], }, 600, function() { /* animation done */ }); }, function(){ // leave animation jQuery('.slidedown').mouseout( function() { setTimeout( function(){ jQuery('.slidedown').stop(true,true).animate( { height: '0px'}, 600, function(){});}, 200 ); // setTimeout ends here }); // mouseout ends here }); });
All i'm trying to achieve is have the div a) stay open if the user mouses from the link to the div b)close if the user moves mouse away from link but not into div and c) close if user moves mouse out of div. I thought the .mouseout function would keep the div open so that i can at least move my mouse over it but it isn't working. Any ideas? I'd be very grateful this has been a headache to me for a week now. Thanks.
You should not use .hover
but .mouseover()
instead for your first method.
You could wrap your link and the div that does the animation in another div and then apply the hover to the parent div instead of the link. This way you will still validate. For example:
<div class="whatever">
<a class="top-link-cart">Show login form</a>
<div class="slidedown">form html goes here</div>
</div>
and the javascript would be:
jQuery(document).ready(function(){
jQuery('.slidedown').hide();
jQuery('.whatever').hover(function(){//to show
jQuery('.slidedown').show('effect', duration in millisecs);
}, function(){//to hide
jQuery('.slidedown').hide('effect', duration in millisecs);
});
});
this uses the jQueryUI for the animation effects, but you could use the .slideDown() and .slideUp() methods as well if all you need is the div to slide up or down
You need to nest your div.slidedown
inside the a.top-link-cart
:
<a class="top-link-cart">Show login form
<div class="slidedown">
The login form HTML
</div>
</a>
Ignoring standards (block elements like <div>
tags shouldn't really be nested inside inline elements like <a>
tags), this will work because when the div.slidedown
expands, so does the parent <a>
.
That way, the mouseout event won't be triggered until the user's mouse leaves the <a>
.
精彩评论