JS Interview: Explain Event Delegation

Matthew Holman
2 min readFeb 18, 2019

--

JS Interview is a series of short articles where we will explore common JavaScript related interview questions. In this article, we will explore event delegation, event bubbling and how we can use them both to our advantage!

What is event delegation?

Event delegation is when a parent element automatically adds event listeners to its children elements. The event listener will fire anytime an event is triggered on the child element, due to event “bubbling” (event propagation).

What is event “bubbling” / event propagation?

When an event is triggered from an element, the event handler / event listener tied to that event is called. When an event is fired on an element that has parent elements, it runs through a “bubbling” phase. During the “bubbling” phase, the browser checks to see if the element that triggered the event has an event handler registered to it. If it does, it runs the event handler. If it does not, it moves to the parent element and checks if it has an event handler registered to it. The browser continues to move up the chain of parent elements, checking for and executing registered event handlers, until it reaches the root element.

Can I prevent event bubbling?

Yes! In your event handler, you can add the stopPropagation() method to the event. For example, you could add the following to an onClick() event handler:

myElement.handleOnClick = (e) => {
e.stopPropagation();
// Add code to handle the even here
}

When would you use event delegation?

Event delegation can be extremely useful when you want to automatically set an event listener on child elements. For example, say you want to add an event listener to all the <li> elements of an <ul>. However, the unordered list is dynamically generated, based on some data received from an API call. It would be impossible to attach an event handler to each <li> element individually, but you could attach it to the <ul> element and it would be delegated to each of the child <li> elements!

Take a look at the code below. We attach a click handler to the parent <ul> and it is automatically delegated to each <li> element:

Hopefully that has cleared up some confusion. If you have any questions, leave a comment below. If you found this article helpful, please give a 👏!

Sources

The Front End Interview Handbook

Stack Overflow

MDN — Events

--

--