Can 2 buttons call the same function and detect which button was pressed?

I have 2 images on a canvas and each image has it’s own button. When the first button is pressed, the first image is selected. When the second button is pressed, the second image is selected.

  button1 = createButton("Select");
  button1.position(160, 350);
  button1.mousePressed(selectImage);
  button2 = createButton("Select");
  button2.position(560, 350);
  button2.mousePressed(selectImage);
}

function selectImage(){
  //button 1 was pressed
  //or
  //button 2 was pressed
}

https://editor.p5js.org/Bassam/sketches/Sz3x2vjAg

1 Like

You can use .bind or .call.

button1.mousePressed(_=> {
   selectImage.call(this, ‘btn-1’);
});

then in your selectImage(btn) check the btn value and call code accordingly.

1 Like

Can 2 buttons call the same function and detect which button was pressed?

Yes, just check for the keyword this inside that callback function: :computer_mouse:

function selectImage() {
  switch (this) {
    case button1:
      print('Button1');
      break;

    case button2:
      print('Button2');
      break;
  }
}

In normal circumstances, the keyword this inside a function holds the reference of the object which had invoked that function. :nerd_face:

3 Likes