Element: mousemove event

The mousemove event is fired at an element when a pointing device (usually a mouse) is moved while the cursor's hotspot is inside it.

Bubbles Yes
Cancelable Yes
Interface MouseEvent
Event handler property onmousemove

Examples

The following example uses the mousedown, mousemove, and mouseup events to allow the user to draw on the canvas.

HTML

<h1>Drawing with mouse events</h1>
<canvas id="myPics" width="560" height="360"></canvas>

CSS

canvas {
  border:1px solid black;
  width: 560px;
  height: 360px;
}

JavaScript

// When true, moving the mouse draws on the canvas
var isDrawing = false;
var x = 0;
var y = 0;

const myPics = document.getElementById('myPics');
const context = myPics.getContext('2d');

// The x and y offset of the canvas from the edge
// of the page.
const rect = myPics.getBoundingClientRect();

// Add the event listeners for mousedown, mousemove, and mouseup
myPics.addEventListener('mousedown', e => {
  x = e.clientX - rect.left;
  y = e.clientY - rect.top;
  isDrawing = true;
});

myPics.addEventListener('mousemove', e => {
  if (isDrawing === true) {
    drawLine(context, x, y, e.clientX - rect.left, e.clientY - rect.top);
    x = e.clientX - rect.left;
    y = e.clientY - rect.top;
  }
});

myPics.addEventListener('mouseup', e => {
  if (isDrawing === true) {
    drawLine(context, x, y, e.clientX - rect.left, e.clientY - rect.top);
    x = 0;
    y = 0;
    isDrawing = false;
  }
});

function drawLine(context, x1, y1, x2, y2) {
  context.beginPath();
  context.strokeStyle = 'black';
  context.lineWidth = 1;
  context.moveTo(x1, y1);
  context.lineTo(x2, y2);
  context.stroke();
  context.closePath();
}

Result

Specifications

Specification Status
UI Events
The definition of 'mousemove' in that specification.
Working Draft
Document Object Model (DOM) Level 3 Events Specification
The definition of 'mousemove' in that specification.
Obsolete

Browser compatibility

No compatibility data found. Please contribute data for "api.Element.mousemove_event" (depth: 1) to the MDN compatibility data repository.

See also