ILIAS ILIAS - 5 months ago 19
Javascript Question

Single event listener for multiple children elements

Consider the following HTML code:

<section>
<div id="left-box"></div>
<div id="middle-box"></div>
<div id="right-box"></div>
</section>


I want to change the color of
<section>
every time one of the above boxes is clicked. I am not presenting the CSSs. Is it possible instead of using 3 event listeners for click events upon the 3 boxes just to use only one? I've heard about fragments. Any idea?

Answer

You can use a single listener on the <section> which contains the three <div> elements, and then check for event.target to see if one of those is clicked. So your code will only run if you click one of the three boxes, and not the parent <section> element.

Here's an example. I added an ID, class and some CSSs just for clarity.

var section = document.getElementById("container");

container.addEventListener("click", function(e) {
    if (e.target.className == "box") {
        // You clicked on a box
        container.style.backgroundColor = e.target.style.backgroundColor;
    }
});

document.getElementById("left-box").style.backgroundColor = "red";
document.getElementById("middle-box").style.backgroundColor = "green";
document.getElementById("right-box").style.backgroundColor = "blue";
#container {
    background-color: yellow;
    display: inline-block;
    padding: 10px;
}

#container > div {
    width: 50px;
    height: 50px;
    margin: 5px;
    border: 1px solid yellow;
    display: inline-block;
}
<section id="container">
    <div class="box" id="left-box"></div>
    <div class="box" id="middle-box"></div>
    <div class="box" id="right-box"></div>
</section>