- Event delegation is a technique in JavaScript that allows you to listen for events on parent elements, rather than individual child elements. This is useful when you have a large number of child elements that you want to attach event listeners to, but you don't want to add listeners to each individual element.
- Instead, you can attach a single event listener to the parent element, and then use the event object to determine which child element was clicked. This can help to improve performance and reduce code complexity.
- Here's an example to illustrate event delegation in JavaScript:
<!DOCTYPE html>
<html>
<head>
<title>Event Delegation Example</title>
</head>
<body>
<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<script>
const list = document.querySelector('#list');
list.addEventListener('click', function (event) {
if (event.target.tagName === 'LI') {
console.log(`Clicked on ${event.target.textContent}`);
}
});
</script>
</body>
</html>
- In this example, we have an unordered list (<ul>) with three list items (<li>). We want to attach a click event listener to each list item, but instead of doing that, we attach a single click event listener to the parent element, the <ul> element.
- In the event listener function, we use the event object to check if the clicked element is an <li> element. If it is, we log a message to the console with the text content of the clicked element.
- By using event delegation, we have reduced the amount of code we need to write and improved the performance of our application. If we had a larger list with many more items, this technique would be even more beneficial.
No comments:
Post a Comment