DEV Community

Daniel Trejo
Daniel Trejo

Posted on

Exploring addEventListeners

Hey, my name is Daniel and I'm a beginner at all this coding stuff. I'm currently enrolled in Flatiron School for Software Engineer. The first phase was predominantly on JavaScript and it already caught my interest. There are so many things you can do with JavaScript. There's iterations, variables, scope, and the one I'm going to be talking about, Events. Events where there first subject I really thought I grasp almost fully and that was a good feeling on it's own.

At first it was a lot to try and take in at once but after a couple times implementing it into my code for project, labs, and challenges. It really helped get it into prospective for me. It peaked my interest the most because the code itself made sense on it's own. For example, if I were to have something in html with the id of Search, if I wanna select that specific id and add a eventlistener to it, I would use either,

document.querySelector("#search")
or
document.getElementById("search")

Both roughly do the same things, however that have a slight difference as well. querySelector selects the first element in the DOM that matches the specified CSS selector. It is more versatile then getElementById however it is lest straightforward a little slower. Using getElementById is more straightforward and it's generally faster when specifically selecting id's. To add an event to the id="search" You would follow

document.getElementById
with
document.getElementById("search").addEventListener("click", function() {
alert("I've been cliked!");
});

The addEventListener piece is giving the search id an event and in our case it's a click event. Now when we click on whatever we have as our search, either a 🔍 or a search button. It will send an alert to the user with whatever you put for the alert to say.

There are tons of different events that you can use like:

  • mouseover

  • click

  • key(any direction)

and so many more that it would take awhile to list them all out here but the fact that there are so many intrigues me. It means that I will constantly be learning and that actually excites me. I would love to pursue as many of those events that I can and not just those but all of coding. I tried so many times to find something that actually interests me and finally I have a profession that actually excites me to learn about.

//Information on eventlisteners
https://www.w3schools.com/js/js_htmldom_eventlistener.asp

Top comments (0)