1

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

});
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Donovant
  • 3,091
  • 8
  • 40
  • 68
  • you can use delegated events which get added to `someel` and match any childnoes you add later. see http://mootools.net/docs/core/Element/Element.Delegation – Dimitar Christoff Apr 09 '14 at 11:31

2 Answers2

3

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.

Dimitar Christoff
  • 26,147
  • 8
  • 50
  • 69
0

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

Sergio
  • 28,539
  • 11
  • 85
  • 132
  • 1
    don't use `class` on its own, its a [reserved identifier](http://msdn.microsoft.com/en-us/library/hh699851%28v=vs.94%29.aspx) and will throw in IE if it's not in quotes. also, mootools supports an events object that can be passed to the constructor - http://jsfiddle.net/dimitar/uND48/ – Dimitar Christoff Apr 09 '14 at 11:27
  • @DimitarChristoff, very true, good point. I think its worth having your answer also, I like the zen style on your fiddle. Will be the first to vote it up :) – Sergio Apr 09 '14 at 13:57
  • Sergio, I meant without class constructor, just adding it via set("html", "come tag/element"); – Donovant Apr 09 '14 at 14:35
  • @Donovant, I will check this later, am in the middle of deadline. Check Dimitar's suggestion. – Sergio Apr 09 '14 at 14:40