Skip to main content
100%

Capturing Mousemove

✓ Published0🌍 Public
Mmbostock
Last edited Feb 9, 2016
Created on Dec 3, 2012

Three div elements display their current mouse coordinates as a visual feedback for dragging. Clicking and holding any div initiates a drag state, where the text inside updates to show the mouse position relative to that specific div’s top-left corner; releasing the mouse clears the active state. The example uses `d3.select` to attach `mousedown` handlers to the divs, and dynamically registers `mousemove` and `mouseup` listeners on the `window` object only while a drag is in progress. It uses `d3.event.preventDefault()` to stop text selection, `d3.mouse` to compute relative coordinates, and `.classed` for styling changes.

AI-generated description

This example demonstrates a simple technique for capturing mousemove and mouseup events that are initiated by a mousedown on an element of interest. The mousemove and mouseup listeners are registered on the window when the first mousedown event is received; thus, these listeners are automatically scoped to the initiating element (div), while still being able to receive mouse events from anywhere in the current window. When the mouseup event is received, the window listeners are deleted.

gpl-3.0 Licensed

Similar vizzes