Event Listeners in JavaScript

Caitlin R
3 min readJun 15, 2021

Event listeners are a very important tool web developers use when writing code in JavaScript to create website functionality.

I’ve learned that .addEventListener() is an integral JavaScript method used on an EventTarget to make a web application “go,” aka have functionality. For example, when you click a button on a website, or submit a search form, an event listener is what triggers something to actually happen.

Here is a very, very simple illustration of how to implement an event listener when building a website:

If you have some HTML code with a button element, with the id of “button,” and you want something cool (or boring, I guess!) to happen when the website user clicks the button, you’ll need to attach an event listener to it. In this example we will use the button’s event listener to delete a different element when it is clicked. We’ll use a ‘div’ element with the id of “element-to-delete” as our element to be deleted here. See these two elements in the body of this very basic HTML below, in lines 12 and 14.

So without any JavaScript Functionality, the page will look like this, but nothing happens yet when you click the button:

Now for making the button work.

In your JavaScript code (in your index.js file in this example), the first thing you need to do in order to create an event listener, is to select the html element you want to attach the event listener to — the EventTarget. In this case, it is the button element - because we want something to happen when the button is clicked (not when the div is clicked, silly). Here’s one way, using query selector, which we will also then use again to select and save the element we want to remove, in the following line.

Now that you’ve saved your HTML elements under constant variables named “button” and “elementToDelete”, you need to add the event listener to the button. Event listeners require 2 minimum parameters:
1) Event Type (i.e. “click,” “submit,” “DOMContentLoaded,” “mouseover,” “copy,” “scroll,” etc. — see the accepted/functional event types on MDN.) and
2) The Listener — aka a callback function that will execute when the “event” happens. This function can be defined directly within the event listener as the parameter, or can be defined separately.

In this example, we will now add an event listener to our button to turn it into a functioning delete button, removing a selected element (elementToDelete) when clicked. We will then simply define our callback function afterwards, starting on line 8, employing the Element.remove() method:

And that’s it, now you have a functioning delete button that deletes the html element from the page when the button is clicked, thanks to a JavaScript event listener. Now, after you click the Delete Button, the “delete me!” div element disappears from the page:

Learn more about the JavaScript EventTarget.addEventListener() method at MDN!

--

--