Jakub Arnold
Jakub Arnold

Reputation: 87240

Prototype equivalent for jQuery live function

I need to bind event listener to all dynamicaly created elements by given css selector.

In jQuery, that would be

$(".foo").live("click", function(e) {
   // bar
});

Is there any equivalent in Prototype for this?

Upvotes: 15

Views: 10355

Answers (2)

kangax
kangax

Reputation: 39188

This is usually done with Event#findElement:

document.observe('click', function(e, el) {
  if (el = e.findElement('.foo')) {
    // there's your `el`
    // might want to stop event at this point - e.stop()
  }
});

Upvotes: 22

robert
robert

Reputation: 869

The correct answer to the question is here: http://gurde.com/2011/08/jquery-live-in-prototype/

The equivalent of the jQuery .live() in Prototype is the Event.on() method:

var handler = document.on(
    'click',
    'div[id^="post-"] .attached-post-thumbnail',
    function(event, element) {
        console.log(this);
        console.log(element);
    }.bind(this)
);

handler.stop();
handler.start();

Within the callback, the this keyword will always refer to the original element (in this case document).

Upvotes: 13

Related Questions