Check if cursor is inside parent element

I have this html

<div class='parent'> <div class='child'></div> </div> 

I want to add mouseover and mouseout events to the parent element, but the problem is that the hover child elemet cursor fires the mouseout event, although it is still inside the parent element. how can I avoid this so that the mouseout event is fired only when the cursor leaves the parent element.

 $(body).on('mouseover', '.parent' , function(){ /* do somthing */}); $(body).on('mouseout', '.parent' , function(){ /* do another somthing */}); 
+5
source share
3 answers

Use mouseenter and mouseleave instead of mouseover and mouseout to help solve your problem.

 $(document).on('mouseenter', '.parent' , function(){ console.log("Mouse Enter"); }); $(document).on('mouseleave', '.parent' , function(){ console.log("Mouse Leave"); }); 

Do not use stopPropagation() , because the dangers of stopping the propagation of events .

Demo

+3
source

You need to stop the event propagation for the child:

 $(body).on('mouseover', '.child' , function(e){ e.stopPropagation(); }); $(body).on('mouseout', '.child' , function(e){ e.stopPropagation(); }); 
+1
source

Use mouseenter / mouseleave events instead of mouseover / mouseout:

 $(body).on('mouseenter', '.child' , function(e){ }); $(body).on('mouseleave', '.child' , function(e){ }); 
0
source

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


All Articles