Q:

How to Check If the Mouse is Over an Element in jQuery

0

How to Check If the Mouse is Over an Element in jQuery

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the CSS :hover Pseudo-class

You can simply use the CSS :hover pseudo-class selector in combination with the jQuery mousemove() to check whether the mouse is over an element or not in jQuery.

The jQuery code in the following example will display a hint message on the web page when you place or remove the mouse pointer over the DIV element's box.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Check If the Mouse is Over an Element</title>
<style>
    div{
        margin: 80px;
        height: 200px;        
        background: orange;
    }  
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $(document).mousemove(function(){
         if($("#myDiv:hover").length != 0){
            $(".hint").text("Mouse is Over the DIV Element.");
        } else{
            $(".hint").text("Mouse is Outside the DIV Element.");
        }
    });
});
</script>
</head>
<body>
    <div id="myDiv"></div>
    <p class="hint"><!-- Hint text will be displayed here --></p>
</body>
</html>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Scroll to the Top of the Page Using jQuery/... >>
<< How to Get the Children of the $(this) Selector in...