JQuery - How to detect a mouse not above #a and #b
You need to keep the "cache" in whether the mouse is in A or B, and finally, you need to check if they are in the "out" state, and then run your fadeOut
function. A warning word that allows the user to move from one to another for a few milliseconds, otherwise you will find that it does not work properly.
This code should do it, with a live example here: http://jsfiddle.net/jzCjD/
var inArr = {a:false,b:false}; $('#a, #b').mouseover(function(){ inArr [$(this).attr('id')] = true; }); $('#a, #b').mouseout(function(){ inArr [$(this).attr('id')] = false; setTimeout(function(){ if(!inArr.a && !inArr.b) $('#box').fadeOut(800) },100); });
you can check here http://jsfiddle.net/XWRZF/2/
var myTimer = false; $("#a ,#b").hover(function(){ //mouse enter clearTimeout(myTimer); },function(){ //mouse leav myTimer = setTimeout(function(){ $("#box").fadeOut(800); },100) });
Wrap them in a parent div and replace #a in your code with # parent-div:
<div id="parent-div"> <div id="a"></div> <div id="b"></div> </div> <div id="box"></div> $("#parent-div").mouseleave(function () { $("#box").fadeOut(800)); });
Otherwise, if you need separate divs, a cache solution should work.
The mouseleave
and mouseout
are mouseout
only after the mouseover
or mousein
, which actually means that in order to determine whether the cursor is hovering over an element using these events, you must first hang so that the events are triggered.
The right way to do this is to link the event handler with all the mouse movement in the document and check the purpose of the event:
var elements = $('#a, #b'); $(document).mousemove(function(e){ if(elements.get().indexOf(e.target) != -1) // you're over a or b });
This way, you donβt have to hover over the element first to fire the mouseout
or mouseleave
.
Here is a live demo: