Check if mouse is inside div

Maarten Wolfsen picture Maarten Wolfsen · Apr 21, 2016 · Viewed 25.7k times · Source

I want to use an if statement to check if the mouse is inside a certain div, something like this:

if ( mouse is inside #element ) {
 // do something
} else {
 return;
}

This will result in the function to start when the mouse is inside #element, and stops when the mouse is outside #element.

Answer

or hor picture or hor · Apr 21, 2016

you can register jQuery handlers:

var isOnDiv = false;
$(yourDiv).mouseenter(function(){isOnDiv=true;});
$(yourDiv).mouseleave(function(){isOnDiv=false;});

no jQuery alternative:

document.getElementById("element").addEventListener("mouseenter", function(  ) {isOnDiv=true;});
document.getElementById("element").addEventListener("mouseout", function(  ) {isOnDiv=false;});

and somewhereelse:

if ( isOnDiv===true ) {
 // do something
} else {
 return;
}