Press Button to Dispaly Text on the Screen

Hi There,

Just trying to make 3 buttons work in P5Js. I am trying to have some text displayed every time you press the button but I am struggling to write this piece of code that will get text displayed. Thast my code so far:
<let button1
let button2
let button3

function setup() {
createCanvas(400, 400);
function draw() {
background(211, 188, 213);
text(‘Digital Welbeing’,115, 30);

button1 = createButton(“What is it?”);
button1.size(100, 50);
button1.position(20, 50);
button1.mousePressed (text);

button2 = createButton(“How to pratice it?”);
button2.size(100, 50);
button2.position(140, 50);

button3 = createButton(“Food for thought”);
button3.size(100, 50);
button3.position(260, 50);

Will be very grateful for some help

Hi @Kitessa,

Welcome to the forum! :wink:

Please format your code by using the </> button when editing a message or use backquotes around the code like ``` code ``` → code

First thing to understand is that the draw function is executed roughly 60 times per second so any operation that need to be done only once (for example the creation of buttons) can be done in the setup function which is made for that.

So you can create your buttons in the setup function like so:

function setup() {
  createCanvas(400, 400);
  button1 = createButton("What is it?");
  button1.size(100, 50);
  button1.position(20, 50);
  // ...

Unless the position and size of the buttons will change during time, you an do it in the setup.

Next you use the mousePressed method for the button. In the documentation it says:

The .mousePressed() function is called once after every time a mouse button is pressed over the element.

Usage: mousePressed(fxn)
fxn: function to be fired when mouse is pressed over the element.

So you passed the text function that will be called whenever the button is pressed. The issue is that the text function accepts 3 arguments not 0 so you have an error. (you can try to call text() alone and see the error).

If you want a text to be toggled when you press the button, simply use a boolean variable and set it to true when the mouse is pressed.

To do something on press you need to pass a function like:

function onButtonPress() {
  alert("Button was pressed!");


If you want a text to be displayed only when the button is pressed then you might also want to look at mouseReleased().