Search code examples
javascriptdommootoolsmootools-events

How do you add an event in Mootools on an element that an object creates?


I have a Mootools class that creates an element. I need to add a click event to that element so that when it is clicked that event fires. How would you do this as that event cannot be set until the object method has fired that creates the original element?


Solution

  • the Element constructor object accepts a special key events

    new Element('a', {
        href: '#',
        text: 'click me',
        events: {
            click: function(event) {
                event.stop();
                this.fade(.4);
            }
        }
    }).inject(document.body);
    

    then, there is event delegation where you can add an event to a parent element that can catch a filter for an element that you can create later.

    and you can actually add all your events to an object before injecting it into the dom anyway, it is probably faster as well. events can also be an object you have prepared before or you can chain .addEvents(someobj)