Reputation: 1195
I have a function that simply changes between two colors when an element is clicked on, I used the same function on the parent and the child elements, the click event works as expected on the parent but not on the child element- why?
<div class="parent red">
<div class="child blue"></div>
</div>
<script scr="text/javascript" defer>
let parent=document.getElementsByClassName("parent")[0];
let child= document.getElementsByClassName("child")[0];
function toggleColor(e){
let background= e.target.classList;
console.log(e.target);
console.log("event fired")
if(background.contains("blue")){
e.target.classList.remove("blue");
e.target.classList.add("red");
console.log("event fired")
}
else if(background.contains("red")){
e.target.classList.remove("red");
e.target.classList.add("blue");
console.log("event fired")
}
}
parent.addEventListener("click",toggleColor,false);
child.addEventListener("click", toggleColor,false);
</script>
Upvotes: 0
Views: 173
Reputation: 2646
I think this is happening because of event propagation. When you click on child element, click handler of child element is triggered followed by click handler of parent element which would be leading to unexpected behavior in your case.
Add e.stopPropagation() to your toggleColor function and everything should work as expected.
Upvotes: 1