How do I make the onclick event work on a button where Parent already has an onlick?

Asked

Viewed 214 times

1

I have a div father who in it occurs an event onclick in div but within that div I want to have an element that also has an event onclick that is triggered without triggering the onclick of div father, for example:

<div onclick="alert('div pai')">
  <p>div pai</p>
  <button onclick="alert('button')">click</button>
</div>

Jsfiddle: https://jsfiddle.net/6q3m8hv0/4/

What happens is when I click on button he calls the function of button and also that of div father, so the question is:

  • It is possible to make the function of the div father is not called?

1 answer

6


Add Event.stopPropagation the code to prevent other events from happening and prevent the flow of events:

<div onclick="alert('div pai')">
  <p>div pai</p>
  <button onclick="alert('button');event.stopPropagation()">click</button>
</div>

You can also check who shot the event and take the necessary actions. For this you can inspect the Event.target

Browser other questions tagged

You are not signed in. Login or sign up in order to post.