Search code examples
javascriptprototypejsdom-events

How Does One Attach A Handler To A Link Which Is Dynamically Loaded?


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();
});

Solution

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

    Prototype: No straightforward way to do .live, see: Prototype equivalent for jQuery live function