DOM events

Making the HTML dance.

Events

Events are generated by the browser when things happen such as the user taking an action.

Today we’re going to focus on the events that are generated when the user clicks on things in the page.

Different from links

We already know about a elements, which cause something to happen when the user clicks them, namely navigating to a different web page.

But what if we want to do something without leaving the page when the user clicks something?

Event handlers

We can register functions that the browser will call when the user clicks on elements within the page.

These functions are called event handlers.

They are functions just like we wrote last semester.

But instead of assigning them to variables so we can call ourselves, we assign them to a special properties of a DOM node so the browser can call them for us.

Looks like this

// Make a variable to keep track of clicks
let count = 0;

// Get the element we want to add a handler to
const thing = document.querySelector('#thing');

// Now assign a function that becomes an event handler
thing.onclick = (e) => {
  thing.innerText = count;
  count++;
};

Or with a named method.

// Make a variable to keep track of clicks
let count = 0;

// Define a function and assign it to a variable as normal
const clickCounter = (e) => {
  e.currentTarget.innerText = count;
  count++;
};

// Now make the named function an event handler
document.querySelector('#thing').onclick = clickCounter;

This has almost exactly the same effect as the code on the previous slide.

Note that when we assign the function to onclick we are not calling it.

The event object

The argument to the event handler is traditionally named e for “event”. It represents all the information about the event.

Usually we only use it to get the currentTarget or the target of the event.

And often all we really care about is that the event happened.