Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the role of pageX Mouse Event in JavaScript?
The pageX property of mouse events returns the horizontal coordinate (X-axis) of the mouse pointer relative to the entire document, including any scrolled content. Unlike clientX, which is relative to the viewport, pageX gives the absolute position within the document.
Syntax
event.pageX
Return Value
Returns a number representing the horizontal pixel coordinate relative to the left edge of the entire document.
Example
Click anywhere on the paragraph to see the mouse coordinates:
<!DOCTYPE html>
<html>
<body>
<p onclick="coordsFunc(event)" style="padding: 20px; background-color: #f0f0f0; cursor: pointer;">
Click here to get the x (horizontal) and y (vertical) coordinates of the mouse pointer.
</p>
<div id="result"></div>
<script>
function coordsFunc(event) {
var x_coord = event.pageX;
var y_coord = event.pageY;
var xycoords = "X coords= " + x_coord + ", Y coords= " + y_coord;
document.getElementById("result").innerHTML = xycoords;
}
</script>
</body>
</html>
pageX vs clientX vs screenX
| Property | Relative to | Includes Scroll? |
|---|---|---|
pageX |
Entire document | Yes |
clientX |
Viewport (visible area) | No |
screenX |
User's screen | N/A |
Practical Use Cases
The pageX property is commonly used for:
- Creating drag-and-drop functionality
- Positioning tooltips or context menus
- Drawing applications that need absolute positioning
- Tracking mouse movement across scrollable content
Browser Compatibility
The pageX property is supported in all modern browsers. For older Internet Explorer versions (IE8 and below), you may need to calculate it using clientX + document.documentElement.scrollLeft.
Conclusion
The pageX property provides the horizontal mouse coordinate relative to the entire document, making it essential for positioning elements and creating interactive web applications. Use it when you need absolute positioning that accounts for page scrolling.
