Understanding Event Bubbling & Event Delegation
Note: This blogpost operates on the assumption that you already know what parent-child element relationships and event listeners are.
JavaScript offers a versatile toolkit that allows users to interact with the webpages in unique ways. Event Bubbling is the concept of a handler first acting upon a specific element in the HTML then making its way up the family branch to its immediate parent all the way to its ancestors, which could mean the entire document or window itself. Even without a specific event handler being called on the parents or above, the event bubbling still occurs.
Because JavaScript interactivity makes changes to the page after its initial load, typically with the user creating new elements on it through mouse or keyboard inputs, bubbling takes into account those new elements. This automatic occurrence allows us to monitor the webpage on the greater scope, as manually adding more and more event listeners becomes cumbersome as the page gets larger.
Above you can see a simple HTML form element with a submit button nested inside a class element, and on the user’s side of things it looks like this;
Now when the form is submitted, a new task should be generated and appended to the list. However, those new tasks were not part of the original HTML. We use JavaScript to create and append them to the DOM.
Event bubbling still allows for potential new elements or nodes to be rendered because the ancestor of the original element that the listener was called on had been made aware of the changes on its descendant.
Event delegation comes into play here when we add a new task “Walk the dog” to the previously empty unordered list element called collection
. Now that new list item element is appended to the DOM with an accompanying delete button.
In order to remove that newly created task from our page, we need to once again take event bubbling into consideration alongside event delegation. In our code, the delete button triggers a remove function, but instead of just calling it on itself, in this case the red X button, it will be called on the parent of the parent of itself (the list item) causing all three to be removed from the UI.
So this concludes a very brief introduction and example of event bubbling and delegation. I thought it was a rather peculiar aspect of coding with JavaScript and wanted to dive deeper into learning about it myself, considering it happens behind the scenes yet influences how we optimize our code for maximum efficiency.
Thank you for taking the time out to read my post. Stay hydrated.