Search code examples
javascriptjqueryevent-bubbling

How to stop event bubbling in JavaScript?


I have this code below and I would like to stop the click function to fire up when I click on the child div, but I can't get it work. What am I missing?

child.addEventListener("click", function(e) {
e.stopPropagation();
});

Here is the CODEPEN where it should be used.


Solution

  • child is a collection of elements (array)... you have to loop trough it:

    for(var i=0; i<child.length; i++){
      child[i].addEventListener("click", function(e) {
        if(e.stopPropagation){e.stopPropagation();}else{e.cancelBubble=true;}
      }, false);
    }