04 April 2018

Custom JavaScript event illustrated

The trigger function is called when user clicks on p, myCustomEvent is bubble up from p to div1 and div2, but not pass on to div3 because of event.stopPropagation();


 <!DOCTYPE html>  
 <head>  
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  
 </head>  
 <style>  
   form, div, p {  
     border-style: solid;  
     border-width: 1px;  
   }  
   p{  
     background-color:green;  
   }  
 </style>  
 <form>  
 FORM  
   <div id="div3">div3  
     <div id="div2">div2  
       <div id="div1">div1  
         <p onclick="trigger(this)">P</p>  
       </div>  
     </div>  
   </div>  
 </form>  
 <script>  
   $(function () {  
     $("#div3").on("myCustomEvent",  
       function (event, arg1, arg2) {  
         alert("div3 will not receive the event");  
       });  
     $("#div2").on("myCustomEvent",   
       function (event, arg1, arg2) {  
         var s = "div2 arg1:" + arg1 + ", arg2:" + arg2;  
         alert(s);  
         event.stopPropagation();  
       });  
     $("#div1").on("myCustomEvent",  
       function (event, arg1, arg2) {  
         alert("div1 caught myCustomEvent and pass it on");  
       });  
   });  
   function trigger(source)  
   {  
     //trigger myCustomEvent which will bubble up to its parents  
     $(source).trigger("myCustomEvent", ["hello", "world"]);  
   }  
 </script>  

No comments:

Post a Comment