How can I check if th...">

JQuery - How to detect a mouse not above #a and #b

HTML code

<div id="a"></div> <div id="b"></div> <div id="box"></div> 

How can I check if the mouse is over #a and #b and then run the function

 $("#a").mouseleave(function () { $("#box").fadeOut(800)); }); 
+6
source share
6 answers

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); }); 
+9
source

like this:

 $("#a, #b").mouseout(function () { $("#box").fadeOut(800); }); 

live demonstration

+2
source

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) }); 
+2
source

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.

+1
source

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:

http://jsfiddle.net/gion_13/NLjjq/

0
source

If you were looking for a simple if statement.

 if ( !$("#a, #b").is(":hover") ) { // not on it! } 

You still, of course, need to relate this, if some event, you can decide:

 $(document).click(function(){ //the snippet from above }); 
0
source

Source: https://habr.com/ru/post/899765/


All Articles