Listening to events

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

Listening to events

Events tell you that something has happened in JavaScript. For example, if a user clicks on something, a click event fires. If the user hits a key on their keyboard, the keydown and keyup events are fired.

You can get a list of all available events at Mozilla Developer Network’s (MDN) Event Reference. Don’t worry about knowing everything on the list now; you’ll learn them as you go through the course.

Listening for events

If a tree falls in the forest and nobody hears it, did the tree fall? The same question can be applied to events—if an event fired and nobody hears it, did the event fire at all?

You need event listeners to listen to events. You can add event listeners to any element in the DOM like this:

Element.addEventListener('event-name', function () {

})

event-name is the name of the event you want to listen to. You can see a complete list in MDN’s Event Reference.

The function is code you want to execute when the event fires. We also call this function the event handler.

Let’s go through an example.

Listening for a click

Let’s say you want to listen for a click event on a <button> element. To do so, you add the click event listener to the button.

const button = document.querySelector('button')

button.addEventListener('click', function () {
  // Do something here
})

Next, you want to make sure your event listener works. To do so, you can do a console.log statement.

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. We know the event listener works.

Logging a click
Logging a click

Does the listener exist?

You can verify the existence of event listeners with Chrome’s or Firefox’s devtools.

For Firefox devtools, open up the Inspector tab. If an event is present on the Element, you’ll see a tiny ev icon on the same line as the opening tag of the Element.

Firefox shows you an ev icon for any element that has event listeners attached to it
Firefox shows you an ev icon for any element that has event listeners attached to it

Firefox will tell you more details about the event listeners attached to the element if you click on the ev icon.

Clicking on the ev shows you details about events attached to the Element
Clicking on the ev shows you details about events attached to the Element

You can also click on the event listener if you want to see the code used.

Clicking on event listener details shows you the code used
Clicking on event listener details shows you the code used

The process to check for event listeners in Chrome’s devtools isn’t as straightforward as the process you see above in Firefox’s devtools.

For Chrome Devtools, you need to open up the console, and type getEventListeners(element), where element is the element you want to check for.

getEventListeners tells you the number of listeners attached to an Element.
getEventListeners tells you the number of listeners attached to an Element.

To make the process easier, you can click on the Element you wish to inspect (the button in this case) in the Elements tab.

Click on the Element to make the inspection process easier
Click on the Element to make the inspection process easier

Once you click on an Element, Chrome allows you to access that element with $0 in the console:

You can access the selected Element with $0
You can access the selected Element with $0

You can then use $0 to check the existence of event listeners:

Checking the existing of event listeners with $0
Checking the existing of event listeners with $0

Changing the DOM through events

Let’s say you have a button in your HTML. You want to change the button’s background color to #bada55. At the same time, you also want to change the body background color to #99aefa.

What’s the best way to do this?

Classes.

First, you create classes to contain the required CSS.

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

button {
  background-color: #1ce;
}

button.is-clicked {
  background-color: #bada55;
}

Second, you create an event listener. In this event listener, you add .button-is-clicked to the body and .is-clicked to the button.

const button = document.querySelector('button')
button.addEventListener('click', function () {
  // Note: document.body does the same as document.querySelector('body').
  const body = document.body

  body.classList.add('button-is-clicked')
  button.classList.add('is-clicked')
})
Body background turns purple and button background turns green when the button is clicked
You can change the DOM through event listeners and classes

Click to change, click again to revert

Let’s say you want to revert the body background-color to transparent and button background-color to #1ce when you click on the button a second time.

You can do so by checking for the presence of the is-clicked class. If button already contains the is-clicked class, remove it; if button does not contain the is-clicked class, add it.

button.addEventListener('click', function () {
  const body = document.body

  if (button.classList.contains('is-clicked')) {
    body.classList.remove('button-is-clicked')
    button.classList.remove('is-clicked')
  } else {
    body.classList.add('button-is-clicked')
    button.classList.add('is-clicked')
  }
})
Reverting styles with classes
Reverting styles with classes

Want a shortcut? See if you can understand why the following works :)

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

The event object

All event listener callbacks accept an argument. This argument is the event object. People usually abbreviate it either to evt or e.

You’ll learn more about the event object in the events deep dive module.

button.addEventListener('click', function (e) {
  // ... Do something here
})

Exercise

Practice adding event listeners and getting them to do things. You’ll use them a lot when you write components. Do the following:

  1. Write an click event listener. Log something into the console so you know the listener works.
  2. Check the existence of the listener with Firefox’s devtools.
  3. Check the existence of the listener with Chrome Devtools.
  4. Add a class to the element when it is clicked. Remove a class from the element when it is clicked again.

Answers

  • Write an click event listener. Log something into the console so you know the listener works.
document.body.addEventListener('click', evt => {
  console.log('Clicked!')
})
  • Add a class to the element when it is clicked. Remove a class from the element when it is clicked again.
const button = document.querySelector('button')
button.addEventListener('click', evt => {
  button.classList.toggle('clicked')
})