Skip to content

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.
end

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

function mouseClicked() 
  if mouseX < 50 then
    -- Code to run if the mouse is on the left.
  end

  if mouseY > 50 then
    -- Code to run if the mouse is near the bottom.
  end
end

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

mouseClicked example 1

local value = 0

function setup()
  size(100, 100)

  describe(
    'A gray square with a black square at its center. The inner square changes color when the user presses and releases a mouse button.'
  )
end

function draw()
  background(200)

  -- Style the square.
  fill(value)

  -- Draw the square.
  square(25, 25, 50)
end

-- Toggle the square's color when the user clicks.
function mouseClicked()
  if value == 0 then
    value = 255
  else
    value = 0
  end
end

mouseClicked example 2

function setup()
  size(100, 100)

  -- Style the circle.
  fill('orange')
  stroke('royalblue')
  strokeWeight(10)

  describe(
    'An orange circle with a thick, blue border drawn on a gray background. When the user presses and holds the mouse, the border becomes thin and pink. When the user releases the mouse, the border becomes thicker and changes color to blue.'
  )
end

function draw()
  background(220)

  -- Draw the circle.
  circle(50, 50, 20)
end

-- Set the stroke color and weight as soon as the user clicks.
function mousePressed()
  stroke('deeppink')
  strokeWeight(3)
end

-- Set the stroke and fill colors as soon as the user releases
-- the mouse.
function mouseReleased()
  stroke('royalblue')

  -- This is never visible because fill() is called
  -- in mouseClicked() which runs immediately after
  -- mouseReleased()
  fill('limegreen')
end

-- Set the fill color and stroke weight after
-- mousePressed() and mouseReleased() are called.
function mouseClicked()
  fill('orange')
  strokeWeight(10)
end

Syntax

mouseClicked()