views:

6297

answers:

4

Consider the following:

<div onclick="alert('you clicked the header')" class="header">
  <span onclick="alert('you clicked inside the header');">something inside the header</span>
</div>

How can I make it so that when the user clicks the span, it does not fire the div's onclick event?

+3  A: 

event.stopPropagation()

EDIT: For IE: window.event.cancelBubble = true

J-P
Does this work in all browsers?
Sam
There's no such thing as the event object in FireFox.
Robert C. Barth
The event object is a parameter of the callback. Actually, there is no such thing as the event object in IE because this object is accessible through window.event instead of being a parameter of the function :-)
Vincent Robert
+1  A: 

According to this page, in IE you need:

event.cancelBubble = true

ajh1138
+1  A: 

keep in mind that window.event is not supported in FireFox, and therefore it must be something along the lines of:

e.cancelBubble = true

Or, you can use the W3C standard for FireFox:

e.stopPropagation();

If you want to get fancy, you an do this:

function myEventHandler(e)
{
    if (!e)
      e = window.event;

    if (e.cancelBubble)
      e.cancelBubble = true;
    else
      e.stopPropagation();
}
Robert C. Barth
+3  A: 

There are two ways to get the event object from inside a function:

  1. The first argument, in a W3C-compliant browser
  2. The window.event object in Internet Explorer

Generally inside a function you would use something like the following:

function(e) {
  var event = e || window.event;
  [...];
}

which would check first one, and then the other and store whichever was found inside the event variable. However in an inline event handler there isn't an e object to use. In that case you have to take advantage of the arguments array which is always available and refers to the complete set of arguments passed to a function:

onclick="var event = arguments[0] || window.event; [...]"

However, generally speaking you should be avoiding inline event handlers if you need to to anything complicated like stopping propagation. Writing your event handlers separately and the attaching them to elements is a much better idea in the medium and long term, both for readability and maintainability.

Gareth