P5.js: How to use a function as an object parameter

I want to make a button object in p5.js. To do this, I would need to use the button’s function as a parameter in the constructor. I tried using this as the constructor:

constructor(ixp, iyp, iw, ih, itext, icolor1, icolor2, ido) {
    this.w=iw; // button width
    this.h=ih; // button height
    this.posX=ixp; // button x postion
    this.posY=iyp; // button y position
    this.text=itext; // button label
    this.color1=icolor1; // button default color
    this.color2=icolor2; // button color when under mouse
    this.do=ido; // button function

with this instance:

b1 = new Button(100,100,80,30,"play",'rgb(0,255,0)','rgb(0,200,0)',function(){background(255,0,255);});

I was able to do something similar in processing.js, but I can’t get the function to work in p5.js.


please post code by pasting it into the

</> Preformatted text

button what give you like
type or paste code here

we can not see where you execute that function,
also would be nice to have a test environment with running code / show
instead we have to make it again just to try / test / play

like https://editor.p5js.org/kll/sketches/ZJQtqSdAj

but the idea is great and works as you can see there,
still can not think of a reasonable use as the function is ‘fixed’ at declaration,
you could just add it to the class ( or child class )

1 Like

The intention of the current button is to change the background while the button is pressed.

1 Like

did you mean




or check my link again

and you still did not repair your posted code above


Okay, got it. Thank you.

1 Like