Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

js click events of nested elements

Tags:

javascript

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()?

like image 746
Chris Avatar asked Jan 26 '16 00:01

Chris


1 Answers

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>
like image 100
Mandera Avatar answered Sep 29 '22 13:09

Mandera