The Event Listener

Daniel Gould
2 min readFeb 4, 2021

One of my favorite features of vanilla javascript is the event listener. It really encapsulates one the most intriguing parts of Javascript for me and that is user engagement. It’s the choose your own adventure for programming and it’s what really opens the door towards more interactive applications.

I’ll start with the first event listener I learned and that is click! Click on this and see what happens!

Before starting an event you have to make sure you’ve selected which element you would like an event to occur on. For our intensive purposes I’ll just make something up:

const click = document.querySelector(“#dom-click”)

In this case we’re just selected an element within our dom that has an ID of dom-click.

From here I would like to change the color of this element to green on a click. The code for that would be:

click.addEventListener(“click”, changeColor)

Here, I’m calling an eventListener on the click element, I’m specifying what event I would like to listen for(in this case “click”) and then I am calling a callback function to execute what I would like to happen when you click that element. Here is the code for the callback function:

function changeColor(e){

e.target.style.color = “green”

}

Here I am using “e” as a parameter for my function. E stands for event in this case. From here I am calling . target to target where the click event is happening and then I am going into the CSS and changing the color of that element. And that’s it, it’s as easy that!

Some of my other favorite event listeners that I discovered on my journey were double-click, mouse-up and mouse-down, but there are so many! Here’s a link to the MDN documentation where you can really explore what else is out there. These are the keys to unlock a truly interactive application.

https://developer.mozilla.org/en-US/docs/Web/API/EventListener.

Also just a snippet of some of the event listeners I included on my last vanilla javascript application:

--

--