Home 03: Events
Content
Cancel

03: Events

After learning about callback functions, it is time for us to check out events.

Events are a way in JavaScript to inform us that something has happened so we can react on it. For example the HTML page has finished loading or the user has pressed the mouse button or a key.

Remember the chapters about the mouse and the keyboard input, these are events that are triggered by the browser and captured by p5.js for us to react on. But we don’t need p5.js to listen for events.

What events are there?

Some of the most common events are:

load

Tells you that a resource, for example the HTML document connected to your JavaScript code, and all its dependent resources (for example images and scripts) have finished loading.

click

Tells you that a mouse button has been pressed and released on an HTML element. It works for all types of pointing devices, for example also Trackballs or Tablets with pens.

If you want to check out the full list of events, you can have a look here.

Event listener

In order to get the info that an event has happened, you need to listen to it. You can either listen to the document, the window or a specific HTML element in JavaScript. If you listen to the document or the window, you will be informed about all events on the page. If you listen to a specific HTML element, you will only get the informations that are connected with this element.

Here is a simple example to listen to the load event. Your callback function will be called as soon as the document have finished loading.

1
2
3
4
5
function onLoadHandler() {
  console.log("Finished loading");
}

window.addEventListener("load", onLoadHandler);

Let’s have another look at an example. Here we want to know if a user has clicked on a specific HTML element. In order to do that, we first get a reference to the object, in our case with getElementById, and add an event listener to the element.

1
<div id="startButton">Start the game</div>
1
2
3
4
5
function onClickHandler() {
  console.log("Start the game!");
}
const startButtonElement = document.getElementById("startButton");
startButtonElement.addEventListener("click", onClickHandler);

If you click the div element now, you can see the message in the console of your browser.

This post is licensed under CC BY 4.0 by the author.
Contents