JavaScript Event Listeners Tutorial

Hey - Nick here! This page is a free excerpt from my $99 course JavaScript Fundamentals.

If you want the full course, click here to sign up and create an account.

I have a 30-day satisfaction guarantee, so there's no risk (and a ton of upside!) in signing up for this course and leveling up your JavaScript developer skills today!

JavaScript developers can use a feature called “event listeners” to make a website’s appearance change with user behavior.

Any interactive website that you’ve ever visited - including Facebook, YouTube, or even my own website - have used event listeners in one way or another.

This tutorial will teach you how to use JavaScript event listeners to build interactive functionality into the websites that you work on.

Table of Contents

You can skip to a specific section of this tutorial on JavaScript event listeners using the table of contents below:

How to Use JavaScript Event Listeners

JavaScript event listeners can be attached to any element within an HTML page. Event listers can also be attached to the document and window objects if you’re looking to create functionality that works over the entire page.

Before you can add an event listener to an HTML element using JavaScript, you first need to select the element using querySelector or querySelectorAll. Let’s select the <button> tag from our index.html and add an event listener to it.

There are two main ways you could select the <button> using JavaScript: by referencing its type (button) or by referencing its class (.btn). Both are shown below.


const theButton = document.querySelector('button');

const button = document.querySelector('.btn');

We will be using the button variable moving forward.

To add an event listener to the button variable, we use the very-appropriately-named method addEventListener. This method accepts two parameters, in this order:

  • type: the event that the listeners will react to
  • listener: the function that will be called when the event occurs. This is more commonly referred to as a callback function

Let’s create our first event listener using the addEventListener method. More specifically, let’s create a popup box that says “You pushed the button!” every time someone clicks on the Click me!!! button.

Here’s what this event listener will look like before we add any arguments:


const button = document.querySelector('.btn');

button.addEventListener();

The first thing we need to do is figure out which event type the event listener should react to. The Mozilla Developer Foundation maintains this excellent resource on JavaScript events.

A quick search of this page reveals that we probably need the click event. This is unquestionably the more important JavaScript event that you will use throughout your career as a web developer.

Next, we need a JavaScript function to create a popup that says “You pushed the button!”. The alert function is a perfect fit, but you can’t pass it directly into the addEventListener method because it only accepts proper functions with defined parameters. However, we can pass in an anonymous function that only contains the alert function, like this:


function (){

alert('You pushed the button!');

}

Adding both of these elements to our addEventListener gives us the following:


const button = document.querySelector('.btn');

button.addEventListener('click', function (){

alert('You pushed the button!');

});

To summarize, there are three steps used in creating JavaScript event listeners:

  1. Select a variable
  2. Listen for an activity on that variable
  3. Do something in response to that activity

There’s a lot more to learn about JavaScript event listeners, so let’s move on to using custom functions as callback functions in JavaScript.

Using Customer Functions as Callback Functions in JavaScript

In our first example of JavaScript event listeners, we created an anonynomous function directly inside of the addEventListener method, like this:


button.addEventListener('click', function (){

alert('You pushed the button!');

});

A more common practice is to create the callback function outside of the addEventListener method. This is both more readable and allows you to use the same callback function in multiple event listeners without repeating code.

To see this in practice, let’s create a callback function called alertUser that triggers the same JavaScript alert as before:


function alertUser(){

alert('You pushed the button!');

}

Now we can pass this function directly into the addEventListener method:


const button = document.querySelector('.btn');

function alertUser(){

alert('You pushed the button!');

}

button.addEventListener('click', alertUser);

Notice that the function is referenced as alertUser and not alertUser(). This is an important distinction because the code would not work if you used alertUser(). Make sure to keep this distinction in mind, as it is a common source of bugs in JavaScript development.

Im summary, referencing a previously- has the same functionality as our original code, but it’s much better in terms of readability and avoiding duplicated code.

How to Remove JavaScript Event Listeners

Just like we used the addEventListener method to add an event listener to an HTML element, we can use the removeEventListener method to remove them.

You need to use the same parameters to remove an event listener as you used to create it. As an example, here is how you would remove the event listener that we created earlier in this tutorial:


button.removeEventListener('click', alertUser);

The removal of JavaScript event listeners is another reason why it’s better to use outside callback functions - it is actually impossible to remove anonymous JavaScript functions created within the addEventListener method.

To be more specific, if we created our event listener using the following code:


button.addEventListener('click', function (){

alert('You pushed the button!');

});

Then it would be impossible to remove this event listener at a later date.

How To Listen For Events On Multiple Elements

It is very common to want to listen for events on multiple HTML elements, but only react to those events with a single callback method. Unfortunately, you can’t simply use the addEventListener on an array of elements generated using the document.querySelectorAll method.

Instead, you need to loop over every element in the array and apply the addEventLister method to them one-by-one. The easiest way to do this is by using the forEach loop.

To see this concept in action, let’s use the mouseover event to log “You just moused over a paragraph!” to the console every time that we move our mouse over one of the <p> tags on our website.

The first thing we need to do is select the <p> tags using the querySelectorAll method. Let’s store them in a variable called paragraphs:


const paragraphs = document.querySelectorAll('p');

Next, we will write a function called mouseoverParagraph that executes console.log('You just moused over a paragraph!'):


const paragraphs = document.querySelectorAll('p');

function mouseoverParagraph (){

console.log('You just moused over a paragraph!');

}

Third, we need to create a function that will be included in the forEach loop to apply the addEventListener method to every element in paragraphs.


const paragraphs = document.querySelectorAll('p');

function mouseoverParagraph (){

console.log('You just moused over a paragraph!');

}

function paragraphListener(paragraph){

	paragraph.addEventListener('mouseover', mouseoverParagraph);

}

The last step is to apply the paragraphListener method to every element in paragraphs using a forEach loop, like this:


const paragraphs = document.querySelectorAll('p');

function mouseoverParagraph (){

console.log('You just moused over a paragraph!');

}

function paragraphListener(paragraph){

	paragraph.addEventListener('mouseover', mouseoverParagraph);

}

paragraphs.forEach(paragraphListener);

Voila! You will now notice that every time that you mouseover a paragraph on the index.html website, the string You just moused over a paragraph! will be logged to the console.

Final Thoughts

This tutorial taught you how to use JavaScript event listeners to build interactive functionality into your HTML pages.

Here is a brief summary of what was discussed in this tutorial:

  • What a JavaScript event is
  • How to use JavaScript event listeners to create interactive functionality based on user activity on a website
  • The process for removing JavaScript event listeners that you added earlier in your script
  • Why you can’t remove event listeners created using anonymous functions
  • How to create event listeners that listen on multiple HTML elements using a forEach loop

As a quick reminder, this page is a free excerpt from my $99 course JavaScript Fundamentals. Click here to sign up now!