Reference mouseWheel()

mouseWheel()

A function that's called once when the mouse wheel moves.

Declaring the function mouseWheel() sets a code block to run automatically when the user scrolls with the mouse wheel:

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

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

function mouseWheel() {
  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. mouseWheel() is always passed a MouseEvent object with properties that describe the mouse scroll event:

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

The event object has many properties including delta, a Number containing the distance that the user scrolled. For example, event.delta might have the value 5 when the user scrolls up. event.delta is positive if the user scrolls up and negative if they scroll down. The signs are opposite on macOS with "natural" scrolling enabled.

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.

Note: On Safari, mouseWheel() may only work as expected if return false; is added at the end of the function.

Examples

Syntax

mouseWheel([event])

Parameters

event
WheelEvent:

optional WheelEvent 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