DEV Community

cmccafferty96
cmccafferty96

Posted on

Learning to love JavaScript Event Listeners

My name is Claire and I'm currently a student at Flatiron studying software engineering. I'll admit, coming into this I considered myself a "tech savvy" individual, but after completing the first week I was very overwhelmed by the amount of information I didn't know or understand. I truly had no idea just how much is going on behind the scenes of even a simple wikipedia page. It changed my perspective on coding in general, as I realized just how much thought goes into creating, whether it's a webpage, an app, or a video game. Which leads me to the main topic of this blog post, event listeners!

I remember when I first read about event listeners in the pre-work, the concept really confused me. I didn't understand how you could write a simple line of code, and then like magic, change something on a webpage. It was after getting through week-one that the concept started to become less abstract and more applicable. I've learned to really love event listeners, specifically because they can make a pretty boring webpage more interactive and/or dynamic, and the fact that there are so many event listeners you can choose from.

The most common example is a "click" event. I'm going to be honest, I was humbled learning that every time you are able to click on something on a website, it's because a developer put it there intentionally. I know that might sounds kind of funny to someone who has experience coding, but as a beginner, I truly thought that the website just knew to do that.

Here is an example of a "click" event in action:

const button = document.getElementById("button")

button.addEventListener("click", () => {
console.log("I was clicked")
})

In this example, we have selected the HTML element with an ID of "button", and added an event listener to it so that when that button is clicked, it will display the message "I was clicked".
This is a very basic example of a click event, but gives you the general idea of how they work. As you continue to develop your programming skills, the functionality of event listeners becomes way more dynamic, and in my opinion, really fun!

Top comments (0)