1

I have something similar to the following:

<div onclick="doSomething()">
   Content...
   <div onclick="doSomethingElse()">
   </div>
</div>

When doSomethingElse() is called, I don't want doSomething() to be called as well.

Searching the web, I found references to event.stopPropagation() and event.cancelBubble(), which prevent the event from bubbling up to parent elements.

Two questions:

  1. How can I get the event object from doSomethingElse()?

  2. Is it necessary to use both event.stopPropagation() and event.cancelBubble(), or has the industry settled on a standard for this?

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • You might consider using event delegation to simplify things: e.g., [this](http://www.sitepoint.com/javascript-event-delegation-is-easier-than-you-think/) – fgshepard Jul 21 '14 at 19:51

2 Answers2

2

1.) You can just pass the event in as the first parameter of the function:

<div onclick="doSomething(event)">
   Content...
   <div onclick="doSomethingElse(event)">
   </div>
</div>

<script>
    function doSomethingElse(e) {
        // Prevent the doSomething event from being propagated after this one:
        e.stopPropagation();

        //OPTIONALLY: Prevent the *default* event from occurring:
        e.preventDefault();
    }
</script>

(Note: the same works in jQuery event bindings)

Example Fiddle


2.) I've started to see a lax in people using cancelBubble and instead switch over to stopPropagation entirely (the prior being used mostly for legacy IE support). Also, the MDN Docs say to use stopPropagation instead since cancelBubble is both "non-standard" and "deprecated" (source).

(Note: stopPropagation alone does not stop default events. For that, you'll want to call event.preventDefault() (source).

Community
  • 1
  • 1
Casey Falk
  • 2,617
  • 1
  • 18
  • 29
  • I had no idea I could just add `event` as a parameter like that. Where did it come from? I'll try it. – Jonathan Wood Jul 21 '14 at 19:53
  • It's always passed through as the first parameter after an event is fired. Since it's JavaScript, you can completely ignore it as a parameter and all will be well lol. – Casey Falk Jul 21 '14 at 19:55
0

you should define `doSomethingElse' as follows:

var doSomethingElse = function(e){
    // e: event object ... so ...
    e.stopPropagation(); // enough
};

you should also pass the event object in your call: doSomethingElse(event)

event.stopPropagation() works on all browsers, as for IE, works as expected on IE9 and later.

Igwe Kalu
  • 14,286
  • 2
  • 29
  • 39