0

I am creating a nested div like the code below

<body>
  <div style='border:solid 1px red' onclick='alert("hi")'>
  Hawaii
    <div style='border:solid 1px blue;margin:10px;' onclick="alert('haha');return false;">Aloha</div>
  </div>
</body>

I would like to show haha when div of aloha is clicked but not bubling to the Hawaii div onclick event, is there a way to achieve it?

EDIT: I forgot to mention I am aware of event bubbling, but is there a way to stop bubbling/cancel propagation for single element?

drhanlau
  • 2,517
  • 2
  • 24
  • 42
  • please see http://stackoverflow.com/questions/5971601/javascript-event-bubbling among many others – akonsu Jan 11 '13 at 05:48
  • sorry I forgot to mention I am aware of event bubbling. But if I just want to disable bubbling for this element, is it possible? – drhanlau Jan 11 '13 at 05:50
  • 1
    I think you need to call stopPropagation (and whatever IE needs too) in your onclick handler after the call to alert. – akonsu Jan 11 '13 at 05:51

1 Answers1

1

event.stopPropagation does this in modern browsers.

In Internet Explorer before version 9 you need to set event.cancelBubble = true instead.

Example:

<div style='border:solid 1px blue;margin:10px;' onclick="alert('haha'); event.stopPropagation(); return false;">Aloha</div>

You can do a lot better if you avoid putting Javascript in HTML attributes.

Paul
  • 139,544
  • 27
  • 275
  • 264
  • I am aware of propagation and event bubbling, is it possible to cancel for one element but not all ? – drhanlau Jan 11 '13 at 05:51
  • @cherhan Yes, you call it (or set it for IE) in the event handler of the element you want to cancel it on. – Paul Jan 11 '13 at 05:52