JavaScript·100 questions

[ITEM 3] QUESTION: Что такое event delegation?

Answer

Event delegation is one of the most powerful and elegant interface design patterns in JavaScript. The essence of this approach is that instead of attaching a separate event handler to each child element, we set just one common handler on their shared parent. This method relies on the event bubbling mechanism, thanks to which a click or any other action on a child node always reaches the parent container.

When such a common handler triggers, two key properties are always available in the event object: event.target and event.currentTarget. The event.target property points to the specific element where the action directly occurred, for example, a specific button inside a list. At the same time, event.currentTarget references the element to which the handler itself is attached, i.e., the parent container. The difference between these properties lies at the core of the pattern's operation.

Event delegation becomes an indispensable tool when working with dynamic content. If a list of elements is constantly updated with new items from a database or a user adds them interactively, the standard approach would require re-attaching handlers to each new element. With delegation, new elements start working automatically because their events bubble up to the old parent.

Since the event bubbles from the target element, the handler on the parent often needs to figure out which exact element was clicked. To filter and check elements, standard DOM API methods such as matches() and closest() are used. The matches('selector') method checks whether an element matches a given CSS selector, and closest('selector') travels up from the target element in search of the nearest ancestor that satisfies the condition, which is especially convenient if the click happened on an icon inside a button.

Was this answer helpful?

More questions in this topic

Related questions from other topics