How to find mouse position relative to the document using jQuery

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the jQuery event.pageX and event.pageY

The jQuery event.pageX can be used to find the mouse position relative to the left edge of the document, whereas the event.pageY can be used to find the mouse position relative to the top edge of the document. 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">
  •     *{
  •         margin: 0;
  •     }
  •     html, body{
  •         height:100%;
  •     }
  • </style>
  • <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
  • <script type="text/javascript">
  • $(document).ready(function() {
  •     $("body").mousemove(function(event){
  •         var relPageCoords = "(" + event.pageX + "," + event.pageY + ")";
  •         $(".mouse-cords").text(relPageCoords);
  •     });
  • });
  • </script>
  • </head>
  • <body>
  •     <p>Coordinates of mouse pointer with respect to the page 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.