Hirvesh
Hirvesh

Reputation: 7982

Making a jQuery Plugin Work On a dynamically added element

Well, I've got this plugin (http://timeago.yarp.com/) which works ok on existing element. However, when I dynamically add an element, the effect isn't applied on that new element. How can I make the plugin work on dynamically added elements?

the syntax for the plugin is:

$("abbr.timeago").timeago();

Upvotes: 3

Views: 2903

Answers (3)

Teknokraten
Teknokraten

Reputation: 154

this is a known problem when adding dynamic elements. You need to rebind the element you've just added.

So for instance:

$.ajax({
  url: "example.html",
  cache: false,
  success: function(html){
    var $jqueryElement = $(html);
    $("abbr.timeago", $jqueryElement).timeago();
    $("#results").append($jqueryElement);
  }
});

The example above rebinds abbr.timeago returned from the example.html and adds them to the DOM.

Upvotes: 6

Steve Jalim
Steve Jalim

Reputation: 12195

Each time your JS adds a new element, just call .timeago() on it.

Upvotes: 0

Rafay
Rafay

Reputation: 31033

not sure but you can try something like this

$("abbr.timeago").ready(function(){

$(this).timeago();

});

Upvotes: 2

Related Questions