The HTML onmousemove event
The HTML onmousemove attribute runs JavaScript when the pointer moves while over the element. It is an inline handler for the mousemove event; in modern code prefer addEventListener('mousemove', …).
Overview
The onmousemove event attribute runs JavaScript when the mouse moves over the element. In JavaScript the event itself is named mousemove — drop the on prefix when you call addEventListener.
It is one of the mouse events. Its handler receives a MouseEvent with details such as the pointer coordinates (clientX/clientY), which button was used, and which modifier keys were held. For input that also covers touch and pen with one code path, the modern pointer events are the recommended replacement.
You can wire this up with the inline onmousemove HTML attribute, but the modern, recommended approach is element.addEventListener('mousemove', handler) in JavaScript. That keeps behavior out of your markup, lets you attach several handlers to the same event, and makes them easy to remove. The inline attribute is fine for quick demos.
Syntax
<element onmousemove="handler()">…</element>
element.addEventListener('mousemove', handler);
Example
<div onmousemove="this.textContent = event.offsetX + ', ' + event.offsetY" style="padding:20px;background:#eef5ff;border-radius:6px;">Move the mouse here</div>
Best practices
- Prefer
element.addEventListener('mousemove', handler)over the inlineonmousemoveattribute — it separates behavior from markup and allows multiple handlers. - Build interactivity on real <button> or link elements so it also works with the keyboard — not on mouse events alone.
- Consider the unified pointer events to handle mouse, touch and pen together.
- Read coordinates and the pressed button from the
MouseEventthe handler receives.
Frequently asked questions
What is the onmousemove event?
mousemove.Does this event work on touch screens?
How do I get the mouse position?
event.clientX and event.clientY (viewport-relative) from the MouseEvent passed to the handler.Should I use the onmousemove attribute or addEventListener?
addEventListener('mousemove', …) in JavaScript. The inline onmousemove attribute works but mixes behavior into the markup and allows only one handler per element.