How to find mouse position relative to an element using jQuery

Topic: JavaScript / jQuery« Prev|Next »

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 mouse position relative to an element. Here's an example:

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>jQuery Find Coordinates of Mouse Pointer</title>
  • <style type="text/css">
  •     #box{
  •         width:400px;
  •         height:300px;
  •         background: #f2f2f2;
  •         border: 1px solid #000;
  •     }
  • </style>
  • <script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
  • <script type="text/javascript">
  •     $(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>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.