开发者

Any jquery plugin which automatic update time for all the posts of a page

I have a page having lots of posts showing time when they were开发者_如何学运维 posted. I want to keep on updating that time after every 1 min. One simple way can be give them a same class and get all the elements after 1 min and update the time. Any better solutions.


You can use a simple plugin like this:

$.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 {
            return t + ' seconds ago';
        }
    }

    var update = function(){
        var now = new Date().getTime();
        $.each(times, function(i, o){
            o.e.html(format(Math.round((now - o.t) / 1000)));
        });
    };

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

    return this;
}

It sets up a function that runs at an interval and updates the elements that you specify. The elements originally contain the time in integer format, i.e. milliseconds since 1970-01-01:

<div class="TimeSince">1314952218779</div>

Usage:

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

The parameter is the update interval in milliseconds. 1000 is once a second, so if you display the time in minutes you would use a larger value, for example every 20 seconds, or 20 * 1000.

The part you would want to improve is the function format, which turns seconds into a human readable format. It now has minutes and seconds ago, but you probably want something like, days, hours or minutes ago.

Demo: http://jsfiddle.net/Guffa/7EsAX/


jquery.timago.js is your friend. You can find it here: http://timeago.yarp.com/


the simplest solution is to have the same selector for all the elements of the posts that need to show the time and update theyr value every x seconds.

UPDATE : Here is a live demo using the above method.
It is available in the form of a jquery plugin too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜