Search code examples
javascripthtmlevent-bubblingevent-delegation

Event bubbling for event delegation


I am trying to implement event delegation with the following code:

<html>
<head>
<script>
document.addEventListener('click', function(e){
    alert(e.target.className);
}, false);
</script>
</head>
<body>
<ul class="list">
    <li class="item">A</li>
    <li class="item">B</li>
    <li class="item">C</li>
    <li class="item">D</li>
</ul>
</body>
</html>

I want the event to bubble so that, when I click on an <li> item, an alert shows item, and then another alert shows list. But this code only gives the alert with item. How can I modify it so that the event bubbles?


Solution

  • Event callback is only triggered once, but it does not mean the event does not bubble. The callback is only executed when the very element listens to the event.

    If you really want the alert to be triggered all the way back to the ancestors, in your callback, add the alerts for the ancestors one by one. You dont have to add listeners to all the ancestors, which would cause consuming more memory.