Search code examples
javascripteventsdelegation

Bubbling issue with delegated event on parent node with JavaScript


I'm having problems getting my event to bubble correctly I believe in a delegated event.

I have some markup like:

<div id="wrapper">
<!-- more HTML -->
  <div class="clear">
    <a href="#">
      Clear completed <span>items</span>
    </a>
  </div>
</div>

I want to add an event to .clear, and so I put put my handling code inside of a delegated event which is attached to #wrapper. My problem is that my event doesn't seem to bubble. In other words:

getElementById('wrapper').addEventListener('click', app.controller.update, true);

app.controller.update = function(e){
  console.log(e.target.nodeName) //returns either A or SPAN
  while(e.target.nodeName !== 'DIV'){
    //Infinite loop because no bubbling is happening
  }
}

Ideas? Yes, I can attach it directly to the element, but I'd like to keep all the events in a single container. And no, no jQuery.


Solution

  • Event bubbling means that an event, raised on a child node can be handled by a parent node (if it is not cancelled by this child node).

    e.target contains an initiator of an event. So, if you click on span or a tag it will contain references to these tags. To check, if a click was initiated in div#clear you can try such a loop:

    var el = e.target || e.srcElement;
    while(el.nodeName !== 'DIV' && (el.id !== 'clear' || el.id !== 'wrapper')) 
    // climb up to parent nodes until clear or wrapper is found
    {
        el = el.parentNode;
    }
    if (el.id == 'clear')
    {
        // Do smth
    }