While talking about JavaScript core concepts, while working with UI Development, "Event Propagation" is one of the most important topic.
In this article, we will be going through concept of Event Propagation- Bubbling, Capturing and Delegation.
Let's suppose a simple UI, where we have a DIV, inside that "DIV" there is a "FORM" and in that form one "BUTTON" is also present.
Now let us write a simple JavaScript code which add EVENT LISTENERS to all those three tags i.e., div, form & button.
- BUBBLING : As the name suggests like bubbles, events will move bottom to top. As per the JS code above, clicking on any item will show it's tagName as an alert.
eventBubbling by Rounit Sinha (codepen.io)
So, Now as you can see the flow in alert is: BUTTON -> FORM -> DIV
- CAPTURING(or TRICKLING) : As we capture anything from top to bottom, so as the name suggests, event will trigger from Top to Bottom
JS CODE for TRICKLING:
=> stopPropagation() METHOD
Now suppose, we don't want to either execute the Bubbling or Trickling, means we want if button is clicked then only onClick Button event triggers.
EVENT DELEGATION :-
Capturing and bubbling allow us to implement one of the most powerful event handling patterns called event delegation.
The idea is that if we have a lot of elements handled in a similar way, then instead of assigning a handler to each of them - we put a single handler on their common ancestor.
Example: Suppose there is an E-Comm app, where we have different categories present, such as MOBILE, HEADPHONE etc (as shown in code)
Now we don’t have to add event listeners to all the categories present. We can add event listeners to only the parent div, which is of class “Products” here.
And now as the tagName for all the categories is “span” then we have filtered only those with tagName “span” and now it will trigger to the pathname of only those with tagName selected.
Read more at Event delegation (javascript.info)
eventDelegation by Rounit Sinha (codepen.io)
Example: Suppose there is an E-Comm app, where we have different categories present, such as MOBILE, HEADPHONE etc (as shown in code)
Now we don't have to add event listeners to all the categories present. We can add event listeners to only the parent div, which is of class "Products" here.
And now as the tagName for all the categories is "span" then we have filtered only those with tagName "span" and now it will trigger to the pathname of only those with tagName selected.
Read more at Event delegation (javascript.info)
Top comments (0)