Detect when a button is being pressed down

Hey, a simple question: if I have an html button, how can I detect when the button is being pressed. I am not interested in doing something when the button is clicked, but instead in doing something for the entire time that the button is being pressed . Sorta like haveing a boolean like isMousePressed , but just for when a html button is being pressed.

Hope my question makes sense somehow?

1 Like
  1. p5js.org/reference/#/p5/select
  2. p5js.org/reference/#/p5.Element/mousePressed
  3. p5js.org/reference/#/p5.Element/mouseReleased

Hey,

You can use a JavaScript event handler for that (next time you can easily search this on internet) :

document.getElementById('button').onclick = function() {
   alert("button was clicked");
}​;​

@GoToLoop, great, thank you! I made a basic example here for reference. Could it be made more elegantly somehow, or do you need a separate function for both mousePressed and mouseReleased like I have done?

var d = 10;
var pressed = false;

function setup() {
  createCanvas(400,400);
  myButton = createButton("press me");
  myButton.mousePressed(begin); 
  myButton.mouseReleased(end); 
}

function draw() {
  background(120);
  ellipse(width / 2, height / 2, d, d);
  if (pressed) d++;
}

function begin() {
  pressed = true;
}

function end() {
  pressed = false;
}

@josephh, thanks. It was not exactly what I meant. I was not interested in detecting a single button click, but instead in doing something for the entire time that the button is being pressed. Perhaps my question was not all that clear…

1 Like

Elegantly I dunno, but shortened surely: :wink:

createButton('Keep pressing me')
  .mousePressed (() => pressed = true)
  .mouseReleased(() => pressed = false);
2 Likes

Thanks, just what I was looking for!