I have a list with div items. each of them redirects to a page when I click it. Now I added a button within the div and I do not want to get redirected when I click the button (i.e. do not execute the parent divs on click event)
<div class='item' onClick="alert('div');">
... div content
<button class='btn' onClick="alert('button');">Action</button>
</div>
Above code should only alert once when I click the button.
EDIT:
I just realized that my actual problem is even one more level up:
<a href='www.google.at'>
<div class='item' onClick="alert('div');">
<button class='btn' onClick="alert('button');event.stopPropagation();">Action</button>
</div>
</a>
I need to prevent the href redirection when I click the button. Is there something similar to event.stopPropagation()?
Original answer
You can accomplish this by calling event.stopPropagation()
<div class='item' onClick="alert('div');">
<button class='btn' onClick="alert('button');event.stopPropagation();">Action</button>
</div>
Answer to edit
Apparently you can stop the propagation to an anchor element by returning false, not sure if this is the proper way, but it works.
<a href='www.google.at'>
<div class='item' onClick="alert('div');">
<button class='btn' onClick="alert('button');event.stopPropagation();return false;">Action</button>
</div>
</a>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With