Q:

How to find mouse position relative to an element using jQuery

0

How to find mouse position relative to an element using jQuery

All Answers

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

Use the jQuery event.pageX and event.pageY

You can use the jQuery event.pageX and event.pageY in combination with the jQuery offset() method to get the position of mouse pointer relative to an element.

Let's take a look at the following example to understand how it basically works:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Coordinates of Mouse Pointer</title>
<style>
    #box{
        width:400px;
        height:300px;
        background: #f2f2f2;
        border: 1px solid #000;
    }
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
    $(document).ready(function() {
        $("#box").mousemove(function(event){            
            var relX = event.pageX - $(this).offset().left;
            var relY = event.pageY - $(this).offset().top;
            var relBoxCoords = "(" + relX + "," + relY + ")";
            $(".mouse-cords").text(relBoxCoords);
        });
    });
</script>
</head>
<body>
    <div id="box"></div>
    <p>Coordinates of mouse pointer with respect to the DIV box are: <strong class="mouse-cords"></strong></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 get substring from a string using jQuery... >>
<< How to find mouse position relative to the documen...