Mouse Position and Coordinates
You'll learn how to pinpoint exactly where the user's mouse cursor is located using different coordinate systems.
When a mouse event occurs, the browser automatically captures the cursor's position in several different ways. Each coordinate property measures from a different reference point, giving you flexibility depending on what you need to build.
Understanding the Four Coordinate Systems
clientX and clientY
These measure the mouse position relative to the visible viewport (the browser window area you can see). If you scroll, these values remain consistent because they ignore scrolling. Think of it like measuring from the edges of your screen.
pageX and pageY
These measure from the top-left corner of the entire document, including scrolled areas. If you scroll down 500 pixels and click, pageY includes that scroll offset. This is like measuring from the very top of a long scroll of paper, not just what's visible through a window.
screenX and screenY
These measure from the top-left corner of your physical screen (the monitor itself). These rarely change unless you move the browser window.
offsetX and offsetY
These measure relative to the target element that triggered the event. If you click a button, offsetX/offsetY tells you where within that button you clicked.
Practical Usage
element.addEventListener('mousemove', function(event) {
console.log('Viewport:', event.clientX, event.clientY);
console.log('Document:', event.pageX, event.pageY);
console.log('Screen:', event.screenX, event.screenY);
console.log('Element:', event.offsetX, event.offsetY);
});
Key Takeaway: Use clientX/Y for viewport-relative positioning, pageX/Y for document-relative tracking, screenX/Y for screen-level data, and offsetX/Y for element-specific interactions.