11 - Events

p5.js Events

Intro & mousePressed

In the earlier chapters, we learned about a p5.js variable called mouseIsPressed, which assumes the value true when the mouse is clicked and false for all other instances.

We also learned that this is not a great way of capturing user input as the execution speed of the draw function can make it hard to get this variable triggered in a reliable way. That’s why there are other ways of handling user input inside p5.js, namely the events, which solves this problem.

Using events, we can capture the user input outside the draw function loop.

There are numerous event functions in p5.js that we can declare to make use of the event system. One of those functions is the mousePressed function.

The idea is similar to the draw and setup functions where we will be declaring this function with this particular name which is treated by p5.js in a special manner (just like setup and draw functions are).

In a p5.js code, the function that we declare under the name mousePressed gets triggered every time the mouse button is clicked. Let’s re-write our previous example that makes use of the mouseIsPressed variable to make use of mousePressed event function instead.

Get hands-on with 1200+ tech skills courses.