Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 622
Jakub Arnold Avatar asked Sep 25 '09 22:09

Jakub Arnold


2 Answers

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()
  }
});
like image 174
kangax Avatar answered Nov 15 '22 16:11

kangax


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).

like image 44
robert Avatar answered Nov 15 '22 15:11

robert