Event Coordinates: pageX, clientX, screenX, and offsetX
You'll learn how to determine exactly where a mouse or pointer event occurred using four different coordinate systems.
Why Multiple Coordinate Systems?
When a user clicks or moves their mouse, the browser needs to tell you where that happened. But "where" can mean different things depending on your reference point—like describing a location as "3 miles from home" versus "at 123 Main Street" versus "in the northeast corner of the room."
The Four Coordinate Properties
clientX and clientY
Coordinates relative to the visible viewport (the browser window's content area). These values don't change if you scroll the page. Think of it as measuring from the top-left corner of what you can currently see.
pageX and pageY
Coordinates relative to the entire document, including any scrolled content. If you've scrolled down 500 pixels, pageY will be 500 pixels higher than clientY at the same visual position. Perfect for positioning elements relative to the document.
screenX and screenY
Coordinates relative to the user's entire screen (monitor). This includes the browser's address bar, taskbar, everything. Rarely used in web development, but useful for opening popup windows at specific screen positions.
offsetX and offsetY
Coordinates relative to the target element itself. If you click 10 pixels from the left edge of a button, offsetX will be 10, regardless of where that button sits on the page.
Practical Example
element.addEventListener('click', (event) => {
console.log(`Client: ${event.clientX}, ${event.clientY}`);
console.log(`Page: ${event.pageX}, ${event.pageY}`);
console.log(`Screen: ${event.screenX}, ${event.screenY}`);
console.log(`Offset: ${event.offsetX}, ${event.offsetY}`);
});
Key Takeaway: Use clientX/Y for viewport positioning, pageX/Y for document positioning, screenX/Y for screen positioning, and offsetX/Y for element-relative positioning—each coordinate system serves a different reference frame.