Tags

Javascript Capture Event

Events in javascript have been a great way to execute tasks based on different types of explicit or implicit action. Events can be attached to an element using the addEventListener method. There are cases where we attach the same type of event to a parent and its descendants. How do we determine the order of event handling? A useful parameter can be utilized to control such behavior.

Default event handling behavior

error loading mdn-example-default.png

Before introducing event capture, it was not the default behavior for event listeners. Once a descendant element of the parent is clicked, as shown in the image above, the order of events will bubble from the target element (the source of the event) to its parent container, as depicted in the console log image above. This is the default way of propagating events that occur in nested elements. 

What is event capturing?

error loading cover-mdn-example.png

Event capturing is another of way of propagating events. We will start with an example, the image which depicts a sample structure of nested elements with their respective labels as its hierarchy. Each element has a click event attached, yet the parent element has the useCapture parameter set to true (the default is false), as shown below:

parent.addEventListener("click", callback, true)
child.addEventListener("click", callback)
inner.addEventListener("click", callback)

If any of the nested elements that belong to the parent are clicked, then event handling order starts to propagate from top to bottom or from parent to descendant, as seen from the console log above. The event handler of the target element (the origin of the event) gets executed in the end. But why use such behavior for event propagation.

Event capturing use case

This behavior is proven to be useful when doing event delegation where the parent takes responsibility for handling events. Through this manner, specific tasks can be associated through conditional targetting of elements using its id, type, etc. This results in clean code and better performance through less resource allotment for the browser since it avoids attaching similar events to individual elements from a list, table, or nested element.

Yet another useful feature

The ability to control such event handling order is a great feature to have on javascript. Such use cases can be a factor on when to use event bubbling or capturing aside from determining its tradeoffs. Take time to think if event capturing suffices your needs or it is better off with the default behavior.

More Posts

SQL: Clustered and Non Clustered Index

Promise: all and allSettled

SQL Joins