WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES

How to find mouse position relative to an element using jQuery

Topic: JavaScript / jQueryPrev|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 src="https://code.jquery.com/jquery-1.12.4.min.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:

Your Feedback:

We would love to hear from you, please drop us a line.