clientY gives a pointer’s vertical coordinate relative to the browser viewport. The viewport’s origin is its visible top-left corner, (0, 0), so the value changes as the pointer moves within the window but not merely because the page scrolls. section 13.1.1
Choose the coordinate system that matches the UI calculation:
- Use clientY for the pointer’s vertical position from the viewport’s top edge. section 13.1.1
- Use pageY for the document-relative position, including scroll; convert with pageY = clientY + window.scrollY. section 13.1.1
- Convert clientY to an element-local vertical coordinate by subtracting rect.top from element.getBoundingClientRect(). section 13.5 section 13.4
Offset a tooltip from the pointer
A mousemove listener reads event.clientY, adds a 20-pixel vertical offset, and assigns the result to tooltip.style.top. The tooltip follows the cursor without covering it. section 13.1.1
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
});
Inspect the complete tooltip implementation, including the mousemove listener, clientY capture, offsets, and CSS positioning. section 13.1.1
clientY also supplies the cursor’s vertical coordinate for geometry: combine it with an element center from getBoundingClientRect(), then use Math.atan2() to calculate an angle for a cursor-following element. section 9.4
