Event delegation on JavaScript

This post is part of the Interview category. The posts in this category give answers to some hiring process questions.

I follow Front-end Developer Interview Questions and use their question list as a theme for these posts.

Question: Explain event delegation in JavaScript.

Event delegation is a technique in JavaScript that lets you handle events for multiple elements using just one event listener that's attached to a parent element. This works through "event bubbling," where events move up from the target element to the parent element.

Event delegation is especially helpful when working with content that's generated dynamically or when there are many elements that need to handle the same type of event. With event delegation, you only need to add one event listener to the parent element instead of adding a listener to each individual element. This can improve your application's performance, as adding too many event listeners can slow it down.

Here's a closer look at how event delegation works in practice:

Imagine the following HTML code:

<ul id="todo-list">
  <li class="todo-item">Take out the trash</li>
  <li class="todo-item">Do the dishes</li>
  <li class="todo-item">Mow the lawn</li>
</ul>

In this example, we have a simple to-do list that's represented by an unordered list with li elements. If we wanted to handle a click event for each to-do item, we might be tempted to add a click event listener to each li element:

const todoItems = document.querySelectorAll('.todo-item');

todoItems.forEach(item => {
  item.addEventListener('click', function() {
    console.log(`You clicked on ${item.textContent}`);
  });
});

But this can be inefficient if the number of to-do items grows large. Instead, we can use event delegation by attaching the click event listener to the parent ul element:

const todoList = document.getElementById('todo-list');

todoList.addEventListener('click', function(event) {
  if (event.target.classList.contains('todo-item')) {
    console.log(`You clicked on ${event.target.textContent}`);
  }
});

In this example, the click event listener is attached to the ul element, and the event object's target property is used to find out which child element was actually interacted with.

Event delegation is also useful for handling form submissions. For instance, imagine the following HTML code:

<form id="signup-form">
  <input type="email" name="email" required>
  <button type="submit">Sign up</button>
</form>

In this example, we have a simple sign-up form with email input and a submit button. If we wanted to handle the form submission, we could attach a submit event listener to the form element:

const signupForm = document.getElementById('signup-form');

signupForm.addEventListener('submit', function(event) {
  event.preventDefault();

  const email = event.target.elements.email.value;
  console.log(`You submitted the form with email ${email}`);
});

In this example, the submit event listener is attached to the form element, and the event object's target property is used to access the form data.

Conclusion:

In summary, event delegation is a technique that allows you to manage events for multiple elements using just one event listener on a parent element. This is made possible through the concept of event bubbling, where events move up from the target element to the parent element. This can lead to improved performance, as it's more efficient than attaching individual event listeners to each element.

We looked at some examples to demonstrate how event delegation can be applied in practice, including click events and form submissions. Event delegation helps to simplify the management of events in your applications, making it a valuable tool for any JavaScript developer.

I hope you found this post informative. If you're interested in learning more about JavaScript and web development, be sure to check out other posts on this blog. There's always something new to discover!