skip to content
Dev Journal

Listening to Events

/ 2 min read

Events in JavaScript notify you when something happens, like a user clicking a button or pressing a key.

To handle these events, you use event listeners. Add an event listener to any DOM element using this syntax:

Element.addEventListener("event-name", function () {
// Code to execute when the event fires
})

Here, event-name is the name of the event you want to listen for, and the function is the code that runs when the event occurs. This function is also known as the event handler.

An example for a button click:

const button = document.querySelector("button")
button.addEventListener("click", function () {
console.log("Button is clicked")
})

With this code, JavaScript logs “Button is clicked” into the console whenever you click the button. This confirms that the event listener works.

Verify event listeners

To verify event listeners, use browser devtools.

  • in Firefox, look for the ev icon in the Inspector tab.
  • in Chrome, use the console command getEventListeners(element).

Changing the DOM with events

You can also change the DOM through events. For example, to change button and body background colors on a click, use CSS classes and add/remove them with event listeners:

First, define the required CSS classes:

body.button-is-clicked {
background-color: #99aefa;
}
button {
background-color: #1ce;
}
button.is-clicked {
background-color: #bada55;
}

Next, add an event listener to the button:

const button = document.querySelector('button');
button.addEventListener('click', function () {
const body = document.body
body.classList.toggle("button-is-clicked")
button.classList.toggle("is-clicked")
})

This code toggles the classes on and off each time the button is clicked, changing the background colors accordingly.

Event Object

Event listener callbacks accept an event object, often abbreviated as e.

Here’s how you can use it:

button.addEventListener('click', function (e) {
// Access event properties with e
});

Summary

  • Event notify you of actions like clicks or key presses.
  • Use addEventListener to handle events.
  • Verify listeners using browser devtools.
  • Change the DOM with event listeners by toggling CSS classes.
  • Event callbacks receive an event object.
  • You can get a list of all available events at Mozilla Developer Network’s ( MDN) Event Reference.