views:

37

answers:

2

How do I attach a handler to the click event of a link, which is dynamically loaded i.e. it is only loaded in response to another action on the page?

N.B. I am asking how to do this using the Prototype JavaScript library, but am not adverse to additional examples in JQuery as well.

In the code below, the link is inside the page fragment that is loaded dynamically:

$$('.alist').invoke('observe', 'click', function(event) {
  var clickedItem = event.findElement('a');
  if (clickedItem) {
    var href = clickedItem.readAttribute('href');
    new Ajax.Updater('detail', href, {
      method: 'get'
    });
  }
  event.stop();
});
+1  A: 

jQuery: Use .live ( http://api.jquery.com/live/ )

Prototype: No straightforward way to do .live, see: http://stackoverflow.com/questions/1479782/prototype-equivalent-for-jquery-live-function

glebm
A: 

You should really use .delegate() rather than .live() in jQuery
see: http://brandonaaron.net/blog/2010/03/4/event-delegation-with-jquery

MrNibbles