Reference mouseMoved()

mouseMoved()

A function that's called when the mouse moves.

Declaring the function mouseMoved() sets a code block to run automatically when the user moves the mouse without clicking any mouse buttons:

function mouseMoved() {
  // Code to run.
}

The mouse system variables, such as mouseX and mouseY, will be updated with their most recent value when mouseMoved() is called by p5.js:

function mouseMoved() {
  if (mouseX < 50) {
    // Code to run if the mouse is on the left.
  }

  if (mouseY > 50) {
    // Code to run if the mouse is near the bottom.
  }
}

The parameter, event, is optional. mouseMoved() is always passed a MouseEvent object with properties that describe the mouse move event:

function mouseMoved(event) {
  // Code to run that uses the event.
  console.log(event);
}

Browsers may have default behaviors attached to various mouse events. For example, some browsers highlight text when the user moves the mouse while pressing a mouse button. To prevent any default behavior for this event, add return false; to the end of the function.

Examples

Syntax

mouseMoved([event])

Parameters

event
MouseEvent:

optional MouseEvent argument.

Notice any errors or typos? Please let us know. Please feel free to edit src/events/mouse.js and open a pull request!

Related References