liveBook · Manning

Mouse-move event

As explained in Web Components in Action

A mouse-move event is a browser-dispatched event indicating movement of a pointing device over a target.

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

How Web Components in Action covers it

How deep it goes
Explains listener placement, callback state, coordinate calculations, boundary handling, and guarded first events.
Examples
Uses a draggable slider and a Web Harp whose strings react to movement distance.
What it assumes
Assumes familiarity with HTML, DOM elements, custom elements, event listeners, and basic JavaScript classes.
What you can do after
Build it from scratch by wiring mousemove listeners, tracking points, constraining a slider, and passing movement data to child components.
How it connects
Connects event listeners with Web Components, DOM coordinates, custom elements, and component state.

Related concepts

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