Home > other >  Parent and child component both have button, when click child button, parent button invoked
Parent and child component both have button, when click child button, parent button invoked

Time:06-05

https://i.stack.imgur.com/JgJTQ.png

I have button here, the parent component is the entire black block, while the child component is the button surrounded by blue. Both have an onclick functionality. When I click the blue button, the parent component onclick effect is triggered instead. How do I trigger the child component onclick effect when I click within the child component?

CodePudding user response:

This is called event bubbling.

when you click the button you're also implicitly clicking the element it is inside.

Basically, when you click an element, it will then proceed to "bubble up" to the top of the DOM, invoking the onClick for every element.

You can prevent this by using event.stopPropagation().

button.addEventListener('click', e => {
  e.stopPropagation();
  // other stuff
});
  • Related