Reference mouseClicked()

mouseClicked()

A function that's called once after a mouse button is pressed and released.

Declaring the function mouseClicked() sets a code block to run automatically when the user releases a mouse button after having pressed it:

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

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

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

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

On touchscreen devices, mouseClicked() will run when a user’s touch ends if touchEnded() isn’t declared. If touchEnded() is declared, then touchEnded() will run when a user’s touch ends and mouseClicked() won’t.

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: mousePressed(), mouseReleased(), and mouseClicked() are all related. mousePressed() runs as soon as the user clicks the mouse. mouseReleased() runs as soon as the user releases the mouse click. mouseClicked() runs immediately after mouseReleased().

Examples

Syntax

mouseClicked([event])

Parameters

event

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