Search code examples
javascriptmootoolsevent-bubblingmootools-events

mootools stop event bubbling when using Event.Delegation (:relay)


I am adding events to links that are loaded via ajax. Here is a simplified example of the html:

<div class="ajax-content">
  <div class="parent">
    <a href="#" class="event-link">Click here</a>
  </div>
</div>

All content within ".ajax-content" is loaded via ajax. I don't want the click event for ".event-link" to bubble up to ".parent". If it was not loaded via ajax I could do this:

$$('.event-link').addEvent('click', function(event){
  event.stopPropagation();
  event.preventDefault();
  //do stuff
});

However, I can't figure out how to accomplish the same behavior with (click:relay). This is what I am trying:

$$('.ajax-content').addEvent('click:relay(.event-link)', function(event){
  event.stopPropagation();
  event.preventDefault();
  //do stuff
});

How do I prevent the click event from firing on '.parent'? (I also tried other syntax - event.stop() and returning false, but they had the same results.)


Solution

  • I was trying to prevent a delegated click event from firing on div.parent. This can be accomplished in my particular situation by adding a check on the event target in the div.parent event:

    $$('.ajax-content').addEvent('click:relay(.event-link)', function(event){
      console.log("hi");
      event.preventDefault();
      //do stuff
    });
    
    $$('.ajax-content').addEvent('click:relay(.parent)', function(event) {
      if (event.target.match('a')) return false;
      console.log("parent");
    });
    

    Thanks to Dimitar for pointing me in the right direction!