How to find mouse position relative to an element using jQuery

  6940 views   2 years ago jQuery

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">
<meta charset="utf-8">
<title>jQuery Get Coordinates of Mouse Pointer</title>
        background: #f2f2f2;
        border: 1px solid #000;
<script src=""></script>
    $(document).ready(function() {
            var relX = event.pageX - $(this).offset().left;
            var relY = event.pageY - $(this).offset().top;
            var relBoxCoords = "(" + relX + "," + relY + ")";
    <div id="box"></div>
    <p>Coordinates of mouse pointer with respect to the DIV box are: <strong class="mouse-cords"></strong></p>


Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]