5

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

Chris
  • 13,100
  • 23
  • 79
  • 162
  • 2
    See MDN [*Event.stopPropagation*](https://developer.mozilla.org/en/docs/Web/API/Event/stopPropagation). – RobG Jan 26 '16 at 00:55
  • This question is a duplicate of [*Howto: div with onclick inside another div with onclick javascript*](http://stackoverflow.com/questions/2385113/howto-div-with-onclick-inside-another-div-with-onclick-javascript). – RobG Jan 26 '16 at 01:03

1 Answers1

10

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>
Mandera
  • 2,647
  • 3
  • 21
  • 26
  • thank you. It works for the click events, but I just realized that my problem is actually one more level up and related to a href. (please check my edited question) – Chris Jan 26 '16 at 01:35
  • 1
    I just discovered event.preventDefault(); :) – Chris Jan 26 '16 at 01:50