Event Delegation
Browser Events: Event Delegation
What is event delegation?
View Answer:
Interview Response: When a parent element provides event listeners to its children, this is known as event delegation. The event listener activates whenever an event fires on the child element due to event bubbling (event propagation).
What is the behavior pattern in terms of event delegation?
View Answer:
Interview Response: In events, the behavior pattern has two parts. First, we add a custom attribute to an element that describes its behavior. Second, a document-wide handler tracks events and acts if an event happens on an attributed element.
Code Example:
<!-- Counter: -->
<input type="button" value="1" data-counter />
<!-- One more counter: -->
<input type="button" value="2" data-counter />
<script>
document.addEventListener('click', function (event) {
if (event.target.dataset.counter != undefined) {
// if the attribute exists...
event.target.value++;
}
});
</script>
What exactly is event bubbling/event propagation?
View Answer:
Interview Response: When an element triggers an event, the event handler/event listener associated with that event gets called. When an event fires on a parent element, it goes through a "bubbling" phase. The browser checks to determine if the element that caused the event has an event handler registered to it during the "bubbling" phase. If it does, the event handler executes. If it does not, it proceeds to the parent element and checks to see if it has an event handler assigned to it. The browser proceeds up the parent element chain, checking for and executing registered event handlers until it reaches the root element.
Is it possible to prevent event bubbling in JavaScript?
View Answer:
Interview Response: You can add the stopPropagation() method to the event in your event handler.
Code Example:
Element.handleOnClick = (event) => {
event.stopPropagation();
// Add code to handle the event here
}
What is a good use-case for event delegation?
View Answer:
Interview Response: Event delegation can be pretty handy when you wish to set an event listener on child elements automatically. Assume you want to add an event listener to all the <li> components in an <ul>. On the other hand, the unordered list gets constructed dynamically based on data obtained from an API call. An event handler could not be attached to each <li> element individually, but it could be attached to the <ul> element and delegated to each of the child <li> elements.
Code Example:
document.getElementById("app").innerHTML = `
<h1>Current Users</h1>
<ul id="itemList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
<li>Item 7</li>
<li>Item 8</li>
</ul>
`;
document.getElementById("itemList").addEventListener("click", (event) => {
alert(event.type);
});