Stay in the loop. Listen to Events.
You can think of the mechanics of this like the process of listening to a radio. You tune in to a specific station, hear a song or a talk show that you were hoping to catch, then you go do something with that information, sing along, discuss with a friend, etc. Event Listeners follow the same steps.
Steps to Effective Listening
Hear A Song
1) Name of the event
2) Callback Function
Dance It Out
The final step, the callback function, can be written as a nested anonymous function inside the event listener or can be a designated function fully defined in a separate function. The callback handles the resulting work you want to happen after an event has occurred. The callback also has access to the event object which contains all sorts of valuable data that can subsequently be used to conditionally perform different work or be saved to a variable and sent to a database.
Listening closely vs generally
More properly called event propagation, bubbling refers to the idea that all HTML child elements can be “heard” by their parents, meaning that any event which takes place on an element can be accessed by any one of their ancestor nodes. An event traverses the DOM upwards from its origin until it reaches the node on which the event listener has been placed.
Consider the following set of nested HTML elements.
We might suppose that in order to respond to a click on the element
<button id=”hello”>Say Hi!</button>, the event listener would need to be connected to that specific button. However, with bubbling, an event listener set on
<div id="div1">would achieve the same effect and would have the added benefit of being able to listen for click events located anywhere else on that div or its child elements.
When choosing an element to target with an event listener, it is helpful to keep in mind events that may be going on in the surrounding environment as we may want to listen to and trigger a response to many at once. In this case we can place an event listener on their closest common ancestor instead of on each individual element. This is referred to as Event Delegation.
There are many ways to accomplish the steps involved in event listening and handling. So it mostly comes down to personal preference for exactly how an event goes from occurring to being reflected on the webpage (as long it the desired result is achieved of course).
Just make sure to remember