Laz
Laz

Reputation: 3538

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

Upvotes: 1

Views: 94

Answers (2)

MrNibbles
MrNibbles

Reputation: 1

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

Upvotes: 0

glebm
glebm

Reputation: 21090

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

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

Upvotes: 1

Related Questions