Things I Learned About JavaScript Events and Listeners
Most recently I completed the 3rd “module” of the Flatiron School - Immersive Software Engineering program in Denver, which was based mostly around JavaScript. One of the biggest takeaways from the last 3 weeks was what I learned about events / event listeners, which I spent about a week learning.
There is still so much I have to learn, but below I will share what I have understood thus far, and identify some key points.
DOM Events
My Definition
Events are something that happens to the DOM during the course of your program being interacted with, and once an event occurs you can then respond to that event with actions of your choosing.
Some Event Types With a Few Common Examples Each
Mouse Events:
click— Describes itself, a click happens
dblclick — A double click
mouseover — The mouse is over the top of an element with a listener attached
Keyboard Events:
keypress — Any key is pressed
keydown — Key is in the pressed position specifically (excludes Shift, Fn, and CapsLock keys)
keyup — Key has been released from pressed position
Form Events (there is only 2):
submit—A form’s submit button was clicked
reset — A form’s reset button was clicked
Learn More About Events
MDN— Introduction to Events
MDN — All Events
JavaScript Event Listeners
My definition
A JavaScript event listener is something that can be attached to ANY kind of HTML element, and ‘listens’ for a specified event to happen. Once that event happens, all of the code inside the ‘.addEventListener()’ method runs, which is the ‘response’ to the event.
An Example of a JavaScript Event Listener in Action
Starting out with some boilerplate HTML code and adding an ‘h1’ and a ‘p’ element:
Then jumping over to our connected JavaScript file, we can grab the ‘p’ element and then attach an event listener to it. Inside the event listener, we first tell it what event to ‘listen’ for, and second we give it an anonymous function (you can also pass it another function you’ve already made instead) to run once that event happens:
Inside of the anonymous function, we tell the ‘innerText’ to change once the click has happened. After starting up our server you should now be able to change the sentence by clicking on it:
That’s it! You can add an event listener to ANY HTML ELEMENT. And you can make that event listener wait for many different kinds of events, and once that event happens, you can respond in ANY way you want! Changing the ‘innerText’ of a ‘p’ tag is only scratching the surface.
Learn More About Event Listeners
MDN — EventTarget.addEventListener()
I hope you found this article useful in some way, thanks for reading! Get out there and listen for events in your projects!