Skip to content

Event Delegation

  • Event delegation is a technique where, instead of adding event listeners to multiple child elements, you attach one listener to their common parent and handle events using event bubbling.
  • Disadvantage: Not all events bubble up.

HTML

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <ul id="items">
            <li id="laptop">laptop</li>
            <li id="car">car</li>
            <li id="phone">phone</li>
        </ul>
    </div>
</body>
<script src="./event-delegation.js"></script>
</html>

JavaScript

js
document.querySelector('#items').addEventListener('click',(e)=>{
    console.log(e);
    if(e.target.tagName==='LI'){
        window.location.href = "/"+e.target.id
    }
})