clientX vs pageX vs screenX vs offsetX in JavaScript
When handling mouse events in JavaScript, determining the exact
location of a cursor click or movement requires choosing the right
coordinate property. While clientX, pageX,
screenX, and offsetX all return horizontal
pixel coordinates (with matching Y counterparts for
vertical measurements), they differ based on their point of origin. This
article breaks down each property’s specific reference frame so you can
accurately position UI elements, track interactions, and manage
layouts.
clientX / clientY: Relative to the Viewport
clientX and clientY measure the mouse
pointer’s position relative to the visible area of the browser window
(the viewport).
- Origin (0, 0): The top-left corner of the browser’s current viewport.
- Scroll Impact: Completely ignores scrolling. If you
scroll down 500 pixels and click at the top-left of the visible screen,
clientXandclientYwill still measure close to0. - Common Use Cases: Fixed-position elements, custom tooltips that follow the cursor on the visible screen, or drag-and-drop overlays.
pageX / pageY: Relative to the Entire Document
pageX and pageY provide coordinates
measured relative to the entire HTML document.
- Origin (0, 0): The top-left corner of the fully rendered webpage, including off-screen content.
- Scroll Impact: Takes scrolling into account. If the
page is scrolled down 300 pixels and you click at the very top edge of
the visible window,
pageYwill evaluate to300. - Common Use Cases: Absolutely positioned elements
appended directly to the
<body>, placing markers on dynamic canvases, or saving interaction positions across a long scrollable document.
screenX / screenY: Relative to the Physical Monitor
screenX and screenY measure coordinates
relative to the user’s physical display screen.
- Origin (0, 0): The top-left corner of the user’s monitor.
- Scroll Impact: Completely independent of browser layout, zoom level, or scrolling.
- Common Use Cases: Multi-window applications, pop-up positioning, and desktop-level interaction mapping.
offsetX / offsetY: Relative to the Target Element
offsetX and offsetY measure the pointer
position relative to the specific HTML element that triggered the
event.
- Origin (0, 0): The top-left corner of the target element’s padding edge.
- Scroll Impact: Independent of page or viewport scrolling; measurements are bounded by the target element itself.
- Common Use Cases: Interactive
<canvas>drawing tools, image zoom previews, and internal component interaction.
Summary Comparison
| Property | Reference Frame (0, 0 Origin) | Affected by Page Scroll? |
|---|---|---|
clientX / clientY |
Top-left corner of the browser viewport | No |
pageX / pageY |
Top-left corner of the HTML document | Yes |
screenX / screenY |
Top-left corner of the physical monitor | No |
offsetX / offsetY |
Top-left corner of the target element | No |