clientX gives a pointer’s horizontal position relative to the browser viewport. The viewport’s origin is its visible top-left corner, (0, 0), so the value remains viewport-relative even when the page is scrolled. section 13.1.1
Use clientX directly for effects positioned near the cursor, such as a tooltip. Add a small pixel offset before assigning the result to CSS left; pair it with clientY for CSS top.
Convert clientX when the calculation needs a different coordinate system:
- Compare it with getBoundingClientRect().left to find the pointer’s horizontal position inside an element: elementX = event.clientX - rect.left. section 13.1.3
- Subtract the slider’s left edge, clamp the result to the track width, and map the resulting progress ratio to a value range. section 13.2.1
Interactive color picker
For a gradient, subtract rect.left from event.clientX and rect.top from event.clientY, divide by the element dimensions, clamp both ratios between 0 and 1, and map them to hue and lightness.
Listing 13.1 A tooltip that follows the mouse pointer
HTML:
<h1>I See Your Pointer</h1>
<h2>The website nobody's talking about!</h2>
<nav>
<button>Home</button>
<button>About</button>
<button>Docs</button>
<button>Contact</button>
</nav>
<div id="tooltip">Welcome to our website!</div>
JavaScript:
document.addEventListener('mousemove', (event) => { #1
const x = event.clientX; #2
const y = event.clientY; #2
const tooltip = document.getElementById('tooltip');
const offsetX = 10; #3
const offsetY = 20; #4
tooltip.style.left = (x + offsetX) + 'px'; #5
tooltip.style.top = (y + offsetY) + 'px'; #5
});
A short mousemove listing shows clientX and clientY driving tooltip position with independent CSS offsets. section 13.1.1
