Add event to dynamically generated element

2.7k Views Asked by At

How can I add an event to an element which was loaded by AJAX.

jQuery has live, but what's the Mootools equivalent?

For example:

window.addEvent('domready', function() {
    // some code which loads new elements by ajax

    // Filter
    $$('.filterButton').addEvent('click', function(event) {
        alert('wow');
    });
});
1

There are 1 best solutions below

0
On

the mootools equivalent is via delegatorElement.addEvent("event:relay(mask)", fn); where event can be standard bubbling (click, mouseover/out/leave/enter etc) or non-bubbling (blur, focus, change etc).

in your code that goes as:

$(document.body).addEvent("click:relay(.filterButton)", function(event, element) {
    console.log(event, element === this); // event obj, true
});

it's better to add the event to an element higher up the dom, like document.id("delegatorId")

more here:

http://mootools.net/docs/core/Element/Element.Delegation

keep in mind, event delegation is in mootools-core since 1.4 - it used to be in mootools-more before that, which means a custom build.