addEventListener() and you!

Event Delegation

What is it? Well I can tell you it is great! Gone are the days of an onMouseOver event watcher on every list item or span on your page. Now you can tell the parents to pay attention to their kids by reminding them to listen to the conversations they little ones are having and reacting appropriately. We do this by using  addEventListener. This brilliant function does just what it says. This one is easier to explain by example, so here goes.

<div id="parent-div">
<span id="child-1">One</span>
<span id="child-2">Two</span>
<span id="child-3">Three</span>
</div>

<script>
// Get the element, add a click listener...
document.getElementById("parent-div").addEventListener("mouseover", function(e) {
// e.target is the moused over element!
// If it was a span item
if(e.target && e.target.nodeName == "SPAN") {
// SPAN item found! Output the ID!
console.log("List item ", e.target.id.replace("child-", ""), " was evented!", e);
}
});
</script>

It is really as simple as that. Now when any child span is moused over the id number for that child will be sent to the console. You can also use specific classes if you use .matches(“className”). Digging deeper into this has me going down the MouseEvent rabbit hole so I know what my next post will be about! I mean who wouldn’t want to learn about MouseEvent.bubbles! BUBBLES!