liveBook · Manning

clientX

As explained in Math for Web Design

clientX is a MouseEvent or Touch property giving a contact's horizontal position relative to the browser viewport.

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

How Math for Web Design covers it

How deep it goes
Explains viewport coordinates, subtraction-based conversion, normalization, scrolling, and control mapping through worked UI calculations.
Examples
Uses cursor tooltips, gradient color pickers, custom sliders, and arrows that rotate toward the pointer.
What it assumes
Assumes JavaScript event listeners and DOM element access while teaching coordinate conversion from viewport positions.
What you can do after
Build cursor-following elements, element-relative interactions, color pickers, sliders, and pointer-directed animations.
How it connects
Connects viewport coordinates with element-relative coordinates, getBoundingClientRect(), sliders, and Math.atan2().

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Math for Web Design. The section links point to the parts of the book it draws on.