How could I have acces to DOM elements p5.js

Hi community,
I’ve watched Handling DOM Events with Callbacks of Coding Train.
In this vidéo, Daniel Shiffman created a button element in sketch.js , using a mousePressed() function to control the randomness of background color.
Instead of creating a dom element in sketch.js, i’d like to link the function to a preexisting element in the index.html. Il dosen’t work as expected, I kept getting the warning message button.mousePressed is not a function. Can anyone help me ? Many thanks!
link to editor p5.js

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/addons/p5.sound.min.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta charset="utf-8" />

  </head>
  <body>
    <button id="click"><p>I am the dysfunctional button </p></button>
    <script src="sketch.js"></script>
  </body>
</html>

sketch.js

let bgc;
let button =document.getElementById('click');

const t =(sketch)=> {
  sketch.setup=()=>{
    sketch.createCanvas(400, 400);
    bgc = sketch.color(30);
    button.mousePressed(sketch.changebgc);
  };
  
  sketch.changebgc=()=>{
      bgc = sketch.color(sketch.random(0,225));
  };
  sketch.draw=()=>{
    sketch.background(bgc);
    sketch.fill(220);
  };
};

let bg = new p5(t);

try something like

let bgc;
let button = document.getElementById("click");

const t =(sketch)=> {
  sketch.setup=()=>{
    sketch.createCanvas(400, 400);
    bgc = sketch.color(30);
    //button.mousePressed(sketch.changebgc);
    button.onclick = sketch.changebgc;
  }
  
  sketch.changebgc=()=>{
      bgc = sketch.color(sketch.random(0,225));
  }
  sketch.draw=()=>{
    sketch.background(bgc);
    sketch.fill(220);
  }
  
}

let bg = new p5(t);

no doubt there are a few ways to do this

1 Like

Yes, it worked. Thanks a lot. But i don’t quite get why mousePressed gonna work when create a dom button in sketch.js, but not in my case ?

i think if you mean if you create a button like this

let button = createButton('mybutt');
button.mousePressed(isbig);

why does the mousePressed work and I think it is because this isn’t a standard dom or html button rather it’s a p5js specific implementation of a button. when you use document.get… you are accessing the actual dom and getting a traditional html button. basically depending on what you are using/accessing you will have to refer to the appropriate documentation.

yeah, when i said "create a button in sketch.js " is like what you demonstrated in the comment, sorry, i was’nt very clear, And thanks again for the enlightenment.