Search code examples
javascriptstoppropagationcancel-button

Accessing Event Object from JavaScript Function


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?


Solution

  • 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).