michaelp0730
1/19/2015 - 6:19 PM

DisplayTime.js

(function($) {
    'use strict';

    var dataName = 'displaytime',
        DisplayTime = function(element, options) {
            this.$element = $(element);
            this.options = $.extend({}, $.fn.displaytime.defaults, options);
            this.init();
        };

    $.fn.displaytime = function(options) {
        return this.each(function(i, el) {
            var $this = $(this),
                data = $this.data(dataName);

            if (!data) {
                $this.data(dataName, (data = new DisplayTime(this, options)));
            }

            if (typeof options === 'string') {
                data[options]();
            }
        });
    };

    DisplayTime.prototype = {
        init: function() {
            this.tick();
            this.start();
        },

        start: function() {
            var that = this;
            this.timeout = setInterval(function() {
                that.tick();
            }, 1000);
        },

        stop: function() {
            clearInterval(this.timeout);
        },

        tick: function() {
            var now = new Date(),
                hour = now.getHours(),
                minute = now.getMinutes();

            if (minute < 10) {
                minute = '0' + minute;
            }

            this.$element.html(hour + ':' + minute);
        }
    };

    $.fn.displaytime.defaults = {};
})(jQuery);