JSByte: JavaScript Event Handlers: How to handle browser events?

What does it mean to "handle an event"?
To put it in simple terms, consider this - let's assume you are interested in attending Web Development meetup events in your local community. To do this, you sign-up for a local meetup called "Women Who Code" and subscribe to notifications. This way, anytime a new meetup is scheduled, you get alerted. That is event handling! The "event" here is a new JS meetup. When a new meetup is posted, the website meetup.com catches this change, thereby "handling" this event. It then notifies you, thus taking an "action" on the event.
In a browser, events are handled similarly. The browser detects a change, and alerts a function (event handler) that is listening to a particular event. These functions then perform the actions as desired.
Event phases
When an event moves through the DOM it is called event propagation. Events happen in two phases: the bubbling phase and the capturing phase. When event lands at its destination, it is said to have reached its target.
In capture phase, also called the trickling phase, the event "trickles down" to the element that caused the event. It starts from the root level element and handler, and then propagates down to the element. The capture phase is completed when the event reaches the target.
In the bubble phase, the event is "bubbled" up to the DOM tree. It is first captured and handled by the innermost handler (the one that is closest to the element on which the event occurred). It then bubbles up (or propagates up) to the higher levels of DOM tree, further up to its parents, and then finally to its root. A trick to remember this is -
trickle down, bubble up
How to listen to an event
There are two ways to listen to an event:
`addEventListener`
inline events, such as `onclick`
Code example -
document.getElementByTag('a').addEventListener('click', onClickHandler);
<a href="#" onclick="onClickHandler">Click me</a>
TL;DR
1. Event phases are capture (DOM -> target), bubble (target-> DOM) and target.
2. Events can be listened to by using addEventListener
or inline methods such as onclick
.
--
Shruti Kapoor
View all recent blogs