Javascript Events and Event Delegation: Advanced Javascript

Vamsi Krishna Kodimela
Angular Simplified
Published in
3 min readJan 22, 2024

--

What is an Event?

An event is any action triggered by the user or any other browser API as the user clicks, scrolls, or types something on the keyboard or some printer, showing a task completion. Events are not just triggers but also carry information such as the element involved, its properties, and the type of event.

How to capture Events?

There are two well-known ways to capture an event:

  • By adding a listener to an element using the “addEventListener” method.
const signupBtn = document.getElementById("signUp");
signupBtn.addEventListener('click',(event)=>{
console.log("Clicked Signup button");
});
  • By using element-level event properties like onclick, onsubmit,…
// HTML
<button onclick="saveData()">Save</button>

// Javascript
const saveData = ()=>{
console.log("Saved Data");
}

Event handlers may seem simple, but imagine creating around 30+ clickable elements that perform the same action. Adding event listeners for each component can make it easier to maintain and understand. Fortunately, “Event Delegation” is a solution for this problem that is already available in Javascript.

Event Delegation

If you want to handle events in a way that is both efficient and easy to manage, consider using “Event Delegation.” By adding just one listener to a common ancestor element, you can capture event bubbles from all its descendants without attaching listeners to each element. This approach can simplify your code and make it more streamlined and organized.

Event Bubbling: Events in the DOM “bubble up” the hierarchy, propagating from the target element to its ancestors. We can even stop the event propagation.

How It Works

  • Attach a single event listener to a common ancestor element.
    When an event occurs on a descendant element, it bubbles up to the ancestor.
  • The ancestor’s event listener checks if the target element matches the criteria.
  • If it matches, the event listener executes the desired logic.
const listContainer = document.querySelector('ul');
listContainer.addEventListener('click', function(event) {
if (event.target.tagName == 'LI') {
console.log('Clicked list item:', event.target.textContent);
}
});

In the above example, we listen to clicks on items in a list using Event Delegation.

--

--