sm21guy
sm21guy

Reputation: 626

auto time increment like on facebook (jquery)

Okay , im want to make something like facebook's auto time increment for posts and notificaitons etc. when the post arrived for example , 5 seconds ago.

How do i use jQuery to make it auto increase without having to parse server for timeago.

It can increase till hours and days.

I have found a script , and tried modifying it , but its not working: Any jquery plugin which automatic update time for all the posts of a page

$.fn.UpdateSince = function(interval) {

    var times = this.map(function(){ return { e: $(this), t: parseInt($(this).html()) }; });

    var format = function(t) {
        if (t > 60) {
            return Math.floor(t / 60) + ' minutes ago'
        } else if(t > 3600){
            return Math.floor(t / 3600) + ' hours ago'
        } else if(t > 86400){
            return Math.floor(t / 86400) + ' days ago'
        } else {
            return t + ' seconds ago';
        }
    }

    var update = function(){
        $.each(times, function(i, o){
            o.e.html(format(Math.round((o.t + 1000))));
        });
    };

    window.setInterval(update, interval);
    update();

    return this;
}

$('.TimeSince').UpdateSince(1000);

Upvotes: 1

Views: 1487

Answers (2)

Isaac Lubow
Isaac Lubow

Reputation: 3573

It looks like you removed the now variable from the original script, which needs to know what time it is in order to run!

The getTime() method returns a value from your system clock - not the server.

Incidentally, you should reverse the order of the conditional in your code - put "days" first, then "hours", then "minutes":

if(t > 86400) {
    return Math.floor(t / 86400) + ' days ago';
} else if(t > 3600) {
    return Math.floor(t / 3600) + ' hours ago';
} else if(t > 60) {
    return Math.floor(t / 60) + ' minutes ago';
} else {
    return t + ' seconds ago';
}

Otherwise, the function will always return "seconds" if t is greater than 60.

Upvotes: 0

Blender
Blender

Reputation: 298196

There'a already a pretty good plugin called timeago that does just this.

Just include it:

<script src="jquery.timeago.js" type="text/javascript"></script>

And add some code:

$('abbr.timeago').timeago();

Your HTML should look something like this:

<abbr class="timeago" title="2008-07-17T09:24:17Z">July 17, 2008</abbr>

Upvotes: 2

Related Questions