Display n time ago on various items using jquery, [issue with new elements generated after the loading the DOM]

StackOverflow https://stackoverflow.com/questions/7471845

  •  22-01-2021
  •  | 
  •  

Question

I am using Jquery plugin http://timeago.yarp.com/ for showing time.

Issue is timeago will not take effect for dynamically generated items.

    $(document).ready(function() {

         $(".timeago").timeago();       // works perfectly fine for the items which are loaded on page load

         //$(".timeago").live(timeago());      // gives me an error ie timeago is not defined

         //$(".timeago").live($(".timeago").timeago());  // gives me an error too much recursion.
         jQuery.timeago.settings.allowFuture = true;
});

From some google search I got to know something ie:

Using live is the same as using bind, except that it is limited only to the events click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, and mouseup.

Now how can do it cause I dont have any click event? How can I bind this?

Was it helpful?

Solution

.live() and .bind() assign callbacks to event. In your case, you don't have an event to assign the function to and so it fails.

You can, in theory, assign your callback to a custom event. You will however have to manually trigger the event (using .trigger()) whenever your item is generated. For example:

$("abbr.timeago").live("timeago", function() {
   $(this).timeago();
});

// ... and in the bit that generates your item
$new_item.trigger("timeago")

Demo: http://jsfiddle.net/ZjuW4/9

Of course, using .live() in this situation is purely academic and does not really serve a good purpose.

If you do have access to the code that's generating the items, you can simply chain in the call to .timeago() as the items are generated, i.e. http://jsfiddle.net/ZjuW4/3/

OTHER TIPS

take a look in this topic here was discussed how to put timeago on dynamically loaded items for example the results of an ajax request.

Activate timeago on newly added elements only

PS: allowFuture does not have anything to do with putting timeago on newly created items on your page. it just allows dates in the future (f.e. "in 3 days", "next week")

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top