JavaScript / JavaScript Events
Event Bubbling and Event Delegation
This tutorial will guide you through the process of event bubbling and delegation in JavaScript. These are crucial concepts for managing complex interactions in nested HTML elemen…
Section overview
5 resourcesExplains event handling and propagation in JavaScript.
Introduction
This tutorial aims to help you understand two crucial concepts in JavaScript: Event Bubbling and Event Delegation. These concepts are key to managing complex interactions in nested HTML elements. By the end of this tutorial, you will be able to:
- Understand and explain what event bubbling is.
- Understand and explain what event delegation is.
- Implement event bubbling and delegation in JavaScript.
Prerequisites: Basic knowledge of HTML, CSS, and JavaScript.
Step-by-Step Guide
Event Bubbling
Event bubbling is a type of event propagation in the HTML DOM API when an event occurs in an element inside another element, and both elements have registered a handle for that event. The event propagation mode determines the order in which elements receive the event.
With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements.
Here is a simple example of event bubbling:
<div onclick="alert('div')">
<p onclick="alert('p')">CLICK ME!</p>
</div>
When you click on the paragraph, you'll see two alerts: one with 'p' and another with 'div'. This happens because the event bubbles from the paragraph (inner element) to the div (outer element).
Event Delegation
Event delegation is a technique of delegating one event handler to the parent element instead of assigning it to the child nodes. The handler is added to one parent and because of event bubbling, events that are triggered on the child nodes are bubbled up and handled at the parent level.
Here is a simple example of event delegation:
<ul id="parent-list">
<li id="post1">Item 1</li>
<li id="post2">Item 2</li>
<li id="post3">Item 3</li>
</ul>
<script>
document.getElementById('parent-list').addEventListener('click', function(e) {
alert('Clicked on item: ' + e.target.innerHTML);
});
</script>
When you click on any list item, you'll see an alert with the clicked item's text. This is because the click event is delegated to the parent list, and it handles clicks for all of its child nodes.
Code Examples
Code Example 1: Event Bubbling
<div id="grandparent" onclick="console.log('grandparent')">
<div id="parent" onclick="console.log('parent')">
<button id="child">Click Me!</button>
</div>
</div>
<script>
document.getElementById('child').addEventListener('click', function() {
console.log('child');
});
</script>
In this example, when you click the button, it'll log 'child', 'parent', and 'grandparent' to the console because of event bubbling.
Code Example 2: Event Delegation
<ul id="fruit-list">
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
</ul>
<script>
document.getElementById('fruit-list').addEventListener('click', function(e) {
if(e.target && e.target.nodeName == "LI") {
console.log(e.target.innerHTML + ' was clicked');
}
});
</script>
In this example, clicking on any list item logs the clicked fruit's name to the console. This is because the click event is delegated to the parent list, and it handles clicks for all of its child nodes.
Summary
In this tutorial, we discussed the concepts of event bubbling and event delegation. We learned that event bubbling is the process where an event propagates up from the target element to the parent elements, and event delegation is a technique where we delegate a single event listener to a parent element instead of assigning it to each child individually.
Practice Exercises
- Exercise 1: Create an HTML page with 3 nested
divelements each with their own click event. Log to the console whichdivwas clicked. - Exercise 2: Create a list of items. When clicked, change the color of the clicked item using event delegation.
- Exercise 3: Modify the above exercise to include a button that adds a new item to the list. Ensure the click event works on the new item.
Additional Resources
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article