Search code examples
jquerypropagation

jquery event bubble not working


I think I understand event bubble but when I put below code into practice, it doesn't seem to work. Alert stops at span level when I expect them to continue beyond that. If someone can point to what I am missing I would appreciate it. BUT I have bigger puzzler(at least to me). What is the point of event bubble? It feels like to me that event bubble should NOT be the default and should be rather an option to turn it on. Can someone kindly give me an example of WHEN auto event bubble is useful?(and please do point out if event bubble is NOT on by default and therefore explains why my code do not get the results that I am expecting).

Huge thank you for everyone as always in advance!!

  <body>
     <div>
         <h1>
        <a href="#">
               <span>Hello</span>
        </a>
         </h1>
     </div>
     <script>
        //window.addEventListener("load",function(){
    //  var els = document.querySelectorAll("*");
    //  for ( var i=0; i< els.length; i++){
    //      els[i].addEventListener("click", function(){
    //      alert('click even fired on the ' + this.nodeName + '  element');
    //      });
    //       }
    //});
        $("span").click(function(){
               alert('click even fired on the ' + this.nodeName + ' element');
    });
     </script>

Further on propagation, given below code, if I only want to match spanOut, I do not want to use bubble method.(probably will have to squeeze in span id on that?). How will bubble method help in this case?

<span> spanOut
   <div>
       divOut
   </div>
        <span>spanIn</span>
            <div>divIn</div>
        <span>spanIn2</span>
   <div>
       divOut2
   </div>
</span>

Solution

  • The event bubbles, not the function bound to the event. The event is actually bubbling, but the parent elements don't have anything bound to them, only the span.

    This fiddle shows how the event bubbles. The alert pops up twice, as there is the actual clicked span, then another span in the hierarchy. The event is triggered on the div, but the div has no handler bound to the event.

    HTML:

    <span>
      <div>
        <span>
          hello
        </span>
      </div>
    </span>
    

    JavaScript:

    $("span").click(function(){
      alert('click even fired on the ' + this.nodeName + ' element');
    });
    

    Event bubbling is mostly useful because typically you don't bind your event to the bottom level element, but an element higher up in the tree. If the event didn't bubble, your top level element may never receive an event trigger.

    Here's another example showing stopping bubbling