A mouse-move event lets a browser component react continuously as the pointer travels across a target. The handler can read coordinates, compare successive positions, and turn movement into dragging, animation, or sound. section 5.3 section 3.6
Useful implementation choices include:
- Listen on the component when movement should affect only that component. section 5.3
- Listen on document when dragging must continue after the pointer leaves the component. section 3.6
- Guard the first event when no previous coordinate exists, then compare current and previous positions. section 5.3
- Convert client coordinates into component-relative positions and clamp them before updating a slider value. section 3.6
Dragging a custom slider
Register mousemove and mouseup on document, and mousedown on the slider. Set isDragging on mousedown, compute the pointer's position relative to the slider, clamp it to the slider width, and update the value while movement continues. section 3.6
Listing 3.25. Adding three event listeners to handle mouse move, up, and down
connectedCallback() {
this.innerHTML = '<div class="bg-overlay"></div><div
class="thumb"></div>';
document.addEventListener('mousemove',
e => this.eventHandler(e)); #1
document.addEventListener('mouseup', e => this.eventHandler(e));
this.addEventListener('mousedown', e => this.eventHandler(e));
this.refreshSlider(this.value); #2
this.setColor(this.backgroundcolor);
}
Inspect the listener placement that keeps dragging active outside the slider while retaining component-local mousedown handling. section 3.6
