my website: http://modernego.info
I have an <a> element named #btn-cart. When offered, it drops down and shows a div named .block-cart. So this is how I want it to go:
If hovered on #btn-cart set .block-cart to display:block;
If hover out on #btn-cart set .block-cart todisplay:none;
If hovered on #btn-cart set .block-cart to display:block;
and then hovered onto .block-cart ignore the mouseleave on #btn-cart.
I got that working with the code below; however, when I set $('.block-cart').fadeOut(200), the .block-cart is set to display:none even if I hover on it.
Also, I am using .live because this cart is run through Ajax and without it the jQuery doesn’t work after the Ajax call. Is there a better way?
jQuery(function($) {
$('#btn-cart').live('mouseenter', function() {
$('.block-cart').css('display','block');
});
//----------------------------------------------
$('.block-cart').live('mouseenter', function() {
var close = false;
$('.block-cart').css('display','block');
});
//----------------------------------------------
$('.block-cart').live('mouseleave', function() {
close = false;
$('.block-cart').fadeOut(200);
});
//----------------------------------------------
if (close != false) {
$('#btn-cart').live('mouseleave', function() {
$('.block-cart').fadeOut(200);
});
}
});
<li class="hover hover-cart-sidebar">
<a href="http://modernego.info/checkout/cart/" class="btn-cart hover-cart" id="btn-cart" title="Cart">
<span class="quantity">0</span>
</a>
<div class="block block-cart">
<div class="block-title">
<strong><span>My Cart</span></strong>
</div>
<div class="block-content">
<p class="empty">Add something to your cart.</p>
</div>
I have done it so many times in so many different ways, but as I think about this question, I think the best way is to hack it with data attributes.
Simplified example:
HTML (simplified/dirty version, added input to check focus/hover on child elements)
JS *(should be optimized to avoid repeated DOM searches, but you get the
* Updated to reflect
fadeOut()instead ofhide()* Updated to use
on()instead ofhover()Fiddle
http://jsfiddle.net/Meligy/GLG6A/ (using
hover()widthhide())http://jsfiddle.net/Meligy/GLG6A/3/ (using
hover()widthfadeOut(), only slight change)http://jsfiddle.net/Meligy/GLG6A/5/ (using
on()on the elements instead ofhover())http://jsfiddle.net/Meligy/GLG6A/6/ (using
on()on the container, more realistic for AJAX)Credit:
Got inspiration from here How do I check if the mouse is over an element in jQuery? and thought it work best and simplest, and it actually did! (in my tests at least)