Many developers may hear about event delegation but not familiar with that. I just wrote and tested some code to illustrate how it works. Event delegation is to add a event listener to the parent instead of the individual node. In this way we can avoid redundant codes for similar listeners.
<head>
<title>delegation</title>
</head>
<body>
<ul id = "parent">
<li id = "l1"> Item 1 </li>
<li id = "l2"> Item 2 </li>
<li id = "l3"> Item 3 </li>
<li id = "l4"> Item 4 </li>
<li id = "l5"> Item 5 </li>
</ul>
<script type="text/javascript">
document.getElementById("parent").addEventListener("click",function(e){
if(e.target && e.target.nodeName == 'LI'){
console.log("List Item", e.target.id.slice(1),"was clicked!");
}
})
</script>
</body>
The test result is as shown below.
<div id = "div2">
<p>Test delegation matching.</p>
<a href="#" class = "classA">link1</a>
<a href="#" class = "classB">link2</a>
</div>
<script>
document.getElementById("div2").addEventListener("click",function(e){
if (e.target && e.target.matches('a.classA')) {
console.log("Anchor was clicked!")
};
})
</script>
The test result:
In summary, event delegation can let parent node perform events on children nodes. It saves lots of event listeners, also makes code simpler and more elegant.