Brad Farberman
2 min readDec 4, 2019

Event Listeners in JavaScript: Listen Up!

Some IRL event listeners

Let’s say someone asked you, “What’s an event listener?” Naturally, you would answer: “That’s somebody in the audience at a concert!” In JavaScript, however, an event listener is something wildly different than a mere music fan taking in a live performance. In js (that’s what the cool kids call JavaScript), an event listener is a method that keeps an ear out for, say, a click or mouseover.

So how would we write it? And how do we use it? To begin, we’ll need to understand where we’ll be “listening.” That would be the DOM, or Document Object Model, so we’ll start like:

document.addEventListener

Next, an event listener takes in two arguments: what we’re listening for and what will happen. So, if we’ve got our ears open for clicks, the first line could start like this:

document.addEventListener(“click”, function(e){

})

As you see, the callback above also has an argument. “e” stands for event. Next, we’ll need to consider a target. We don’t want our website to respond to clicks just anywhere on the page, right? So we can target, say, a like button! And we can do it with an if statement. Check it out:

document.addEventListener(“click”, function(e){

if (e.target.id === “like_button”){

}

})

To finish our if statement, and finish up in general, we can make it so that likes increment by 1 when the like button is clicked. Looks like this:

document.addEventListener(“click”, function(e){

if (e.target.id === “like_button”){

document.getElementById(“likes”).innerHTML = parseInt(document.getElementById(“likes”).innerHTML) + 1

}

})

And that’s a brief intro to event listeners! Don’t forget to be a good listener ;)

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Brad Farberman
Brad Farberman

Written by Brad Farberman

Brad Farberman is a musician and web developer based in Brooklyn, NY.

No responses yet

Write a response