Thursday, 30 October 2014

X minutes ago functionality using jquery and knockout

In this article I am going demonstrate simple time ago functionality by using jquery.timeago plugin and knockout js.

1)      Create a HTML page and add the jquery, jquery.timeago and knockout library:

<script src=""></script>

    <script src=""></script>

    <script src=""></script>


2)      Create a viewmodel and a custom binding handler in knockout:


        $(function () {


            var viewModel = {


                arr: [{

                    msgdate: new Date()

                }, {

                    msgdate: new Date()




            ko.bindingHandlers.timeago = {

                update: function (element, valueAccessor) {

                    var value = ko.utils.unwrapObservable(valueAccessor());


                    var $this = $(element);


                    $this.attr('title', value.toISOString());


                    if ($'timeago')) {

                        var datetime = $.timeago.datetime($this);

                        var distance = (new Date().getTime() - datetime.getTime());

                        var inWords = $.timeago.inWords(distance);


                        $'timeago', { 'datetime': datetime });


                    } else {









3)      Bind knockout viewmodel with a div in html to display and automatically update the time.

    <div data-bind="foreach: arr">

        <div class="timeago" data-bind="timeago: msgdate"></div>



Thanks for reading this article.

Read more articles.


1 comment:

Nannie Co Pam said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.