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.


No comments: