JavaScript Coordinates
JavaScript provides various ways to track coordinates of elements, mouse events, and touch inputs on a webpage. These coordinates help in drag-and-drop, animations, drawing on canvas, and more.
1. Different Types of Coordinates in JavaScript
| Property | Reference Point | Example Usage |
|---|---|---|
clientX, clientY | Viewport (excluding scroll) | Tracking mouse within the visible screen |
pageX, pageY | Full document (including scroll) | Detecting a mouse on a scrolled page |
screenX, screenY | Screen (monitor) | Multi-screen tracking |
offsetX, offsetY | Element relative (padding box) | Canvas drawing, element interaction |
getBoundingClientRect() | Element relative (box model) | Finding an element’s position |
2. Mouse Event Coordinates
Example: Track Mouse Position
š What’s the difference?
clientX/Y→ Relative to viewport (ignores scroll).pageX/Y→ Relative to entire page (includes scroll).screenX/Y→ Relative to physical screen (monitor).
3. Getting an Element’s Position
Example: Get Position of a Button
š¹ getBoundingClientRect() returns an object with the element’s size and position relative to the viewport.
4. Click Position Relative to an Element
Example: Track Clicks Inside a Box
š¹ offsetX/Y gives coordinates relative to the clicked element (not the whole page).
5. Tracking Touch Coordinates (Mobile Devices)
Example: Get Touch Position
š¹ event.touches contains all fingers currently touching the screen.
6. Dragging an Element Using Coordinates
Example: Make an Element Draggable
š¹ This drags the element by updating its left and top positions.
7. Summary of JavaScript Coordinate Systems
| Coordinate Type | Reference | When to Use? |
|---|---|---|
clientX/Y | Viewport | Mouse tracking in visible area |
pageX/Y | Full document | Handling scrolling pages |
screenX/Y | Physical screen | Multi-monitor setups |
offsetX/Y | Element | Drawing inside elements |
getBoundingClientRect() | Element (viewport-based) | Get element's position |
š Need help with coordinates? Let me know! š

