Question

How can I add an event (by Mootools) to an element just created via set("html"), and inserted through the DOM?

$(document).addEvent("domready", function(){
      $(someel).set("html", "<p class='someclass'></p>");
      $$("someclass").somefn("click", function(){...});//somefn: that add the "click" event to the <p> element

});
Was it helpful?

Solution

So. via event delegation, adding a single event to top most element:

document.addEvent("domready", function(){
    $('foo').addEvents({
        'click:relay(p.someclass)': function(){
            alert('very well');
        }
    }).set("html", "<p class='someclass'>click me</p>");
});

or chaining it like so, adding events to all elements directly:

document.addEvent("domready", function(){
    $('foo').set("html", "<p class='someclass'>click me</p>")
        .getElements('.someclass').addEvent('click', function(){
            alert('chained');
        });
});

method 1 is more performant and allows for adding/removal or matching elements without rebinding.

OTHER TIPS

You should use the Element constructor. A code example could be like this:

$(document).addEvent("domready", function () {
    var pElement = new Element('p', {           // create a new element
        'class': 'someclass',                     // give it a class
        'html': 'Click me to make me alive...'  // give it some HTML
    });

    $('someel').adopt(pElement);                // have someone adopt it
    pElement.addEvent("click", function () {    // add event to it here OR in the Element constructor
        alert('Hello world!'); 
    });
});

Example

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top