How do the onclick event work on a button where the parent already has an onlick?

0

I have a div parent that in it occurs an event onclick in the div integer, however within that div I want to have an element that also has a onclick event that is triggered without triggering onclick of% parent%, for example:

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

JSFiddle: link

What happens is that when I click on div it calls the function of button and also that of button parent, then the question is:

  • Is it possible to make the function of div parent not be called?
asked by anonymous 15.08.2018 / 19:26

1 answer

5

Add event.stopPropagation to 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 still check who fired the event and take the necessary actions. For this you can inspect the event.target

    
15.08.2018 / 19:30