jQuery PageX/Y Event

Wednesday, June 20, 2012

The jQuery event pageX and pageY provides the position of the mouse pointer, relative to the left edge (pageX) and/or right edge (pageY) of the document.


Syntax

event.pageX
event.pageY


Basic Example

In the following jQuery example, the event.pageX and event.pageY will be used to display the X and Y position of the mouse cursor.


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $(document).mousemove(function (e) {
    $("#pos").text("X: "
      + e.pageX + " | Y: " + e.pageY);
  });
});
</script>
</head>
<body>     
<div id="pos"></div>
</body>
</html>




You can also get the pageX and pageY coordinates for a specific HTML element by making some simple changes to the jQuery code as follows.


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("#pos").mousemove(function (e) {
    var x = e.pageX - this.offsetLeft;
    var y = e.pageY - this.offsetTop;
    $("#pos").text("X: "
      + x + " | Y: " + y);
  });
});
</script>
</head>
<body>     
<div id="pos"></div>
</body>
</html>


Did you find the page informational and useful? Share it using one of your favorite social sites.

Recommended Books & Training Resources

Pro jQuery JavaScript and jQuery: The Missing Manual Professional jQuery