Skip to content

Instantly share code, notes, and snippets.

@krsjoseph
Created November 10, 2016 20:12
Show Gist options
  • Save krsjoseph/73013c51ae091220503df8e7f9b0d51f to your computer and use it in GitHub Desktop.
Save krsjoseph/73013c51ae091220503df8e7f9b0d51f to your computer and use it in GitHub Desktop.
jquery clock widget
<div id="clock_pos"></div>
<div id="clock_canada"></div>
<div id="clock_usa"></div>
$(document)
.ready(function () {
$('#clock_pos').jClocksGMT({title: 'Port Of Spain', offset: '-4', skin: 5});
$('#clock_usa').jClocksGMT({title: 'Northbrook, USA', offset: '-6', skin: 5});
$('#clock_canada').jClocksGMT({title: 'Saskatoon, Canada', offset: '-6', skin: 5});
});
/***************************************************************************************************************************************************************
* _ ________ __ ________ _________
* (_) ____/ /___ _____/ /_______/ ____/ |/ /_ __/
* / / / / / __ \/ ___/ //_/ ___/ / __/ /|_/ / / /
* / / /___/ / /_/ / /__/ ,< (__ ) /_/ / / / / / /
* __/ /\____/_/\____/\___/_/|_/____/\____/_/ /_/ /_/
* /___/
*
* NAME: jClocksGMT.js
* VERSION: 2.0.2
* LAST UPDATE: 2016.04.26
*
* Author Information:
* Name: Richard McMaster
* Email: r@kingkode.com
* Location: Houston, Texas, United States
* Website: http://kingkode.com/jclocksgmt-js/
* __ _ __ __
* / /__(_)___ ____ _/ /______ ____/ /__
* / //_/ / __ \/ __ `/ //_/ __ \/ __ / _ \
* / ,< / / / / / /_/ / ,< / /_/ / /_/ / __/
* /_/|_/_/_/ /_/\__, /_/|_|\____/\__,_/\___/
* /____/
*
* Plugin Website: http://www.github.com/mcmastermind/jClocksGMT
*
* Change Log:
* 2.0.2: Fixed digital only display
* 2.0.1: Added image path parameter for images not in plugin directory
* 2.0: Complete overhaul of code for increased accuracy and stability
* - NEW! 5 clock skins to choose from
* - NEW! Timestamp formatting options
* - NEW! Date display with formatting options
* - NEW! DST parameter for those locations that do not observe DST
* - Addressed international DST issues
* - Minimized initial markup
* - Unique class names to avoid common class declarations
* 1.2: Fixed severely flawed Daylight Saving Time calculation
* 1.1: Added automatic Daylight Saving Time calculation
*
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*
* Description:
* jQuery based analog and digital clock(s) using GMT offsets. Requires jQuery Rotate plugin.
*
* Documentation:
* Default options:
* title: 'Greenwich, England', String: Title of location (defaults to Greenwich, England)
* offset: '0', String: Set Standard GMT offset (+5.5, -4, 0, etc) (do not consider daylight savings time)
* dst: true, Boolean: Does the location observe daylight savings time (set FALSE if location does not need to observe dst )
* digital: true, Boolean: Display digital clock
* analog: true, Boolean: Display analog clock
* timeformat: 'hh:mm A', String: Time format (see below for formatting options)
* date: false, Boolean: Display date
* dateformat: 'MM/DD/YYYY', String: Date format (see below for formatting options)
* angleSec: 0, Integer: Starting angle of second hand
* angleMin: 0, Integer: Starting angle of minute hand
* angleHour: 0, Integer: Starting angle of hour hand
* skin: 1, Integer: Set 1 of 5 included skins for the analog clock
* imgpath: '' String: Set path of images
*
* Common offsets by time zone: (only use the number after GMT: GMT-2 = offset: '-2'
* Daylight Saving Time converted automatically)
* GMT-12 Eniwetok
* GMT-11 Samoa
* GMT-10 Hawaii
* GMT-9 Alaska
* GMT-8 PST, Pacific US
* GMT-7 MST, Mountain US
* GMT-6 CST, Central US
* GMT-5 EST, Eastern US
* GMT-4 Atlantic, Canada
* GMT-3 Brazilia, Buenos Aries
* GMT-2 Mid-Atlantic
* GMT-1 Cape Verdes
* GMT 0 Greenwich Mean Time
* GMT+1 Berlin, Rome
* GMT+2 Israel, Cairo
* GMT+3 Moscow, Kuwait
* GMT+4 Abu Dhabi, Muscat
* GMT+5 Islamabad, Karachi
* GMT+6 Almaty, Dhaka
* GMT+7 Bangkok, Jakarta
* GMT+8 Hong Kong, Beijing
* GMT+9 Tokyo, Osaka
* GMT+10 Sydney, Melbourne, Guam
* GMT+11 Magadan, Soloman Is.
* GMT+12 Fiji, Wellington, Auckland
*
* To find specific GMT offsets,
* goto: http://www.timeanddate.com/time/zone/
* search: location
* use: Current Offset
* if location is currently observing DST, add 1 to offset
*
* Time Formatting:
* HH 19 24-hour format of hour with leading zero (two digits long).
* hh 07 12-hour format of hour with leading zero (two digits long).
* H 19 24-hour format of hour without leading zeros.
* h 7 12-hour format of hour without leading zeros.
* mm 01 Minutes with the leading zero (two digits long).
* m 1 Minutes without the leading zero.
* ss 08 Seconds with the leading zero (two digits long).
* s 8 Seconds without the leading zero.
* a pm Lowercase am or pm.
* A PM Uppercase AM or PM.
* SSS 095 Milliseconds with leading zeros (three digits long).
* S 95 Milliseconds without leading zeros.
*
* Date Formatting:
* YYYY 2016 Four-digit representation of the year.
* YY 16 Two-digit representation of the year.
* MMMM April Full textual representation of the month.
* MMM Apr Three letter representation of the month.
* MM 04 Month with the leading zero (two digits long).
* M 4 Month without the leading zero.
* DDDD Friday Full textual representation of the day of the week.
* DDD Fri Three letter representation of the day of the week.
* DD 01 Day of the month with leading zero (two digits long).
* D 1 Day of the month without leading zeros.
*
* Initialization:
* Javascript:
* $('#clock_hou').jClocksGMT({ title: 'Houston, TX, USA', offset: '-6', skin: 2 });
* Markup:
* <div id="clock_hou"></div>
*
**************************************************************************************************************************************************************/
(function($) {
$.fn.extend({
jClocksGMT: function( options )
{
// plugin default options
var defaults =
{
title: 'Greenwich, England',
offset: '0',
dst: true,
digital: true,
analog: true,
timeformat: 'hh:mm A',
date: false,
dateformat: 'MM/DD/YYYY',
angleSec: 0,
angleMin: 0,
angleHour: 0,
skin: 1,
imgpath: ''
}
// merge user options with defaults
var options = $.extend(defaults, options);
return this.each(function()
{
// set offset variable per instance
var offset = parseFloat(options.offset);
// get id of element
var id = $(this).attr('id');
// add class to main element
$(this).addClass('jcgmt-container');
// create label
$("<div />", { text: options.title, class: "jcgmt-lbl" }).appendTo("#" + id);
if( options.analog )
{
// create clock container
$("<div />", { class: "jcgmt-clockHolder" }).appendTo("#" + id);
// create hour hand
$("<div />", { class: "jcgmt-rotatingWrapper" }).append($("<img />", { class: "jcgmt-hour", src: options.imgpath + "images/jcgmt-" + options.skin + "-clock_hour.png" })).appendTo("#" + id + ' .jcgmt-clockHolder');
// create min hand
$("<div />", { class: "jcgmt-rotatingWrapper" }).append($("<img />", { class: "jcgmt-min", src: options.imgpath + "images/jcgmt-" + options.skin + "-clock_min.png" })).appendTo("#" + id + ' .jcgmt-clockHolder');
// create sec hand
$("<div />", { class: "jcgmt-rotatingWrapper" }).append($("<img />", { class: "jcgmt-sec", src: options.imgpath + "images/jcgmt-" + options.skin + "-clock_sec.png" })).appendTo("#" + id + ' .jcgmt-clockHolder');
// create clock face
$("<img />", { class: "jcgmt-clock", src: options.imgpath + 'images/jcgmt-' + options.skin + '-clock_face.png' }).appendTo("#" + id + ' .jcgmt-clockHolder');
}
// create digital clock container
$("<div />", { class: "jcgmt-digital" }).appendTo("#" + id);
//create date container
$("<div />", { class: "jcgmt-date" }).appendTo("#" + id);
// initial hand rotation
$('#' + id + ' .jcgmt-sec').rotate( options.angleSec );
$('#' + id + ' .jcgmt-min').rotate( options.angleMin );
$('#' + id + ' .jcgmt-hour').rotate( options.angleHour );
// get timezone by gmt offset
Date.prototype.getTimezoneByOffset = function( offset, y, m, d )
{
var date = new Date; // get date
if( y ) // if has date params
{
date = new Date( y, m, d ); // get date with params
}
var utc = date.getTime() + ( date.getTimezoneOffset() * 60000 ); // get local offset
var dateGMT = new Date( utc + ( 3600000 * offset ) ); // get requested offset based on local
return dateGMT;
}
// check if daylight saving time is in effect
Date.prototype.stdTimezoneOffset = function()
{
var jan = this.getTimezoneByOffset( offset, this.getFullYear(), 0, 1 );
var jul = this.getTimezoneByOffset( offset, this.getFullYear(), 6, 1 );
return Math.max( jan.getTimezoneOffset(), jul.getTimezoneOffset() );
}
// checkes if DST is in effect
Date.prototype.isDST = function()
{
var date = this.getTimezoneByOffset(offset);
return date.getTimezoneOffset() < this.stdTimezoneOffset();
}
// date formatter
Date.prototype.format = function( format )
{
var D = "Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday".split(","),
M = "January,February,March,April,May,June,July,August,September,October,November,December".split(",");
var self = this;
return format.replace(/a|A|Z|S(SS)?|ss?|mm?|HH?|hh?|D{1,4}|M{1,4}|YY(YY)?|'([^']|'')*'/g, function(str) {
var c1 = str.charAt(0),
ret = str.charAt(0) == "'"
? (c1=0) || str.slice(1, -1).replace(/''/g, "'")
: str == "a"
? (self.getHours() < 12 ? "am" : "pm")
: str == "A"
? (self.getHours() < 12 ? "AM" : "PM")
: str == "Z"
? (("+" + -self.getTimezoneOffset() / 60).replace(/^\D?(\D)/, "$1").replace(/^(.)(.)$/, "$10$2") + "00")
: c1 == "S"
? self.getMilliseconds()
: c1 == "s"
? self.getSeconds()
: c1 == "H"
? self.getHours()
: c1 == "h"
? (self.getHours() % 12) || 12
: (c1 == "D" && str.length > 2)
? D[self.getDay()].slice(0, str.length > 3 ? 9 : 3)
: c1 == "D"
? self.getDate()
: (c1 == "M" && str.length > 2)
? M[self.getMonth()].slice(0, str.length > 3 ? 9 : 3)
: c1 == "m"
? self.getMinutes()
: c1 == "M"
? self.getMonth() + 1
: ("" + self.getFullYear()).slice(-str.length);
return c1 && str.length < 4 && ("" + ret).length < str.length
? ("00" + ret).slice(-str.length)
: ret;
});
}
// create new date object
var dateCheck = new Date().getTimezoneByOffset( offset );
// check for DST
if( options.dst && dateCheck.isDST() )
{
offset = offset + 1;
}
// clock interval
setInterval(function ()
{
// create new date object
var nd = new Date().getTimezoneByOffset( offset );
// time string variable
var timeStr = nd.format( options.timeformat );
// update analog clock if enabled
if( options.analog )
{
// rotate second hand
$('#' + id + ' .jcgmt-sec').rotate( nd.getSeconds() * 6 );
// rotate minute hand
$('#' + id + ' .jcgmt-min').rotate( nd.getMinutes() * 6 ) ;
// rotate hour hand
$('#' + id + ' .jcgmt-hour').rotate( ( nd.getHours() * 5 + nd.getMinutes() / 12 ) * 6 );
// update title for tooltip
$('#' + id + ' .jcgmt-clockHolder').attr( 'title', timeStr );
}
// update digital clock if enabled
if( options.digital )
{
$('#' + id + ' .jcgmt-digital').html( timeStr );
$('#' + id + ' .jcgmt-digital').attr( 'title', timeStr );
}
// update date if enabled
if( options.date )
{
var dateStamp = nd.format( options.dateformat );
$('#' + id + ' .jcgmt-date').html( dateStamp );
$('#' + id + ' .jcgmt-date').attr( 'title', dateStamp );
}
}, 1000);
});
}
});
})(jQuery);
// VERSION: 2.3 LAST UPDATE: 11.07.2013
/*
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*
* Made by Wilq32, wilq32@gmail.com, Wroclaw, Poland, 01.2009
* Website: http://jqueryrotate.com
*/
(function($) {
var supportedCSS,supportedCSSOrigin, styles=document.getElementsByTagName("head")[0].style,toCheck="transformProperty WebkitTransform OTransform msTransform MozTransform".split(" ");
for (var a = 0; a < toCheck.length; a++) if (styles[toCheck[a]] !== undefined) { supportedCSS = toCheck[a]; }
if (supportedCSS) {
supportedCSSOrigin = supportedCSS.replace(/[tT]ransform/,"TransformOrigin");
if (supportedCSSOrigin[0] == "T") supportedCSSOrigin[0] = "t";
}
// Bad eval to preven google closure to remove it from code o_O
eval('IE = "v"=="\v"');
jQuery.fn.extend({
rotate:function(parameters)
{
if (this.length===0||typeof parameters=="undefined") return;
if (typeof parameters=="number") parameters={angle:parameters};
var returned=[];
for (var i=0,i0=this.length;i<i0;i++)
{
var element=this.get(i);
if (!element.Wilq32 || !element.Wilq32.PhotoEffect) {
var paramClone = $.extend(true, {}, parameters);
var newRotObject = new Wilq32.PhotoEffect(element,paramClone)._rootObj;
returned.push($(newRotObject));
}
else {
element.Wilq32.PhotoEffect._handleRotation(parameters);
}
}
return returned;
},
getRotateAngle: function(){
var ret = [];
for (var i=0,i0=this.length;i<i0;i++)
{
var element=this.get(i);
if (element.Wilq32 && element.Wilq32.PhotoEffect) {
ret[i] = element.Wilq32.PhotoEffect._angle;
}
}
return ret;
},
stopRotate: function(){
for (var i=0,i0=this.length;i<i0;i++)
{
var element=this.get(i);
if (element.Wilq32 && element.Wilq32.PhotoEffect) {
clearTimeout(element.Wilq32.PhotoEffect._timer);
}
}
}
});
// Library agnostic interface
Wilq32=window.Wilq32||{};
Wilq32.PhotoEffect=(function(){
if (supportedCSS) {
return function(img,parameters){
img.Wilq32 = {
PhotoEffect: this
};
this._img = this._rootObj = this._eventObj = img;
this._handleRotation(parameters);
}
} else {
return function(img,parameters) {
this._img = img;
this._onLoadDelegate = [parameters];
this._rootObj=document.createElement('span');
this._rootObj.style.display="inline-block";
this._rootObj.Wilq32 =
{
PhotoEffect: this
};
img.parentNode.insertBefore(this._rootObj,img);
if (img.complete) {
this._Loader();
} else {
var self=this;
// TODO: Remove jQuery dependency
jQuery(this._img).bind("load", function(){ self._Loader(); });
}
}
}
})();
Wilq32.PhotoEffect.prototype = {
_setupParameters : function (parameters){
this._parameters = this._parameters || {};
if (typeof this._angle !== "number") { this._angle = 0 ; }
if (typeof parameters.angle==="number") { this._angle = parameters.angle; }
this._parameters.animateTo = (typeof parameters.animateTo === "number") ? (parameters.animateTo) : (this._angle);
this._parameters.step = parameters.step || this._parameters.step || null;
this._parameters.easing = parameters.easing || this._parameters.easing || this._defaultEasing;
this._parameters.duration = 'duration' in parameters ? parameters.duration : parameters.duration || this._parameters.duration || 1000;
this._parameters.callback = parameters.callback || this._parameters.callback || this._emptyFunction;
this._parameters.center = parameters.center || this._parameters.center || ["50%","50%"];
if (typeof this._parameters.center[0] == "string") {
this._rotationCenterX = (parseInt(this._parameters.center[0],10) / 100) * this._imgWidth * this._aspectW;
} else {
this._rotationCenterX = this._parameters.center[0];
}
if (typeof this._parameters.center[1] == "string") {
this._rotationCenterY = (parseInt(this._parameters.center[1],10) / 100) * this._imgHeight * this._aspectH;
} else {
this._rotationCenterY = this._parameters.center[1];
}
if (parameters.bind && parameters.bind != this._parameters.bind) { this._BindEvents(parameters.bind); }
},
_emptyFunction: function(){},
_defaultEasing: function (x, t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b },
_handleRotation : function(parameters, dontcheck){
if (!supportedCSS && !this._img.complete && !dontcheck) {
this._onLoadDelegate.push(parameters);
return;
}
this._setupParameters(parameters);
if (this._angle==this._parameters.animateTo) {
this._rotate(this._angle);
}
else {
this._animateStart();
}
},
_BindEvents:function(events){
if (events && this._eventObj)
{
// Unbinding previous Events
if (this._parameters.bind){
var oldEvents = this._parameters.bind;
for (var a in oldEvents) if (oldEvents.hasOwnProperty(a))
// TODO: Remove jQuery dependency
jQuery(this._eventObj).unbind(a,oldEvents[a]);
}
this._parameters.bind = events;
for (var a in events) if (events.hasOwnProperty(a))
// TODO: Remove jQuery dependency
jQuery(this._eventObj).bind(a,events[a]);
}
},
_Loader:(function()
{
if (IE)
return function() {
var width=this._img.width;
var height=this._img.height;
this._imgWidth = width;
this._imgHeight = height;
this._img.parentNode.removeChild(this._img);
this._vimage = this.createVMLNode('image');
this._vimage.src=this._img.src;
this._vimage.style.height=height+"px";
this._vimage.style.width=width+"px";
this._vimage.style.position="absolute"; // FIXES IE PROBLEM - its only rendered if its on absolute position!
this._vimage.style.top = "0px";
this._vimage.style.left = "0px";
this._aspectW = this._aspectH = 1;
/* Group minifying a small 1px precision problem when rotating object */
this._container = this.createVMLNode('group');
this._container.style.width=width;
this._container.style.height=height;
this._container.style.position="absolute";
this._container.style.top="0px";
this._container.style.left="0px";
this._container.setAttribute('coordsize',width-1+','+(height-1)); // This -1, -1 trying to fix ugly problem with small displacement on IE
this._container.appendChild(this._vimage);
this._rootObj.appendChild(this._container);
this._rootObj.style.position="relative"; // FIXES IE PROBLEM
this._rootObj.style.width=width+"px";
this._rootObj.style.height=height+"px";
this._rootObj.setAttribute('id',this._img.getAttribute('id'));
this._rootObj.className=this._img.className;
this._eventObj = this._rootObj;
var parameters;
while (parameters = this._onLoadDelegate.shift()) {
this._handleRotation(parameters, true);
}
}
else return function () {
this._rootObj.setAttribute('id',this._img.getAttribute('id'));
this._rootObj.className=this._img.className;
this._imgWidth=this._img.naturalWidth;
this._imgHeight=this._img.naturalHeight;
var _widthMax=Math.sqrt((this._imgHeight)*(this._imgHeight) + (this._imgWidth) * (this._imgWidth));
this._width = _widthMax * 3;
this._height = _widthMax * 3;
this._aspectW = this._img.offsetWidth/this._img.naturalWidth;
this._aspectH = this._img.offsetHeight/this._img.naturalHeight;
this._img.parentNode.removeChild(this._img);
this._canvas=document.createElement('canvas');
this._canvas.setAttribute('width',this._width);
this._canvas.style.position="relative";
this._canvas.style.left = -this._img.height * this._aspectW + "px";
this._canvas.style.top = -this._img.width * this._aspectH + "px";
this._canvas.Wilq32 = this._rootObj.Wilq32;
this._rootObj.appendChild(this._canvas);
this._rootObj.style.width=this._img.width*this._aspectW+"px";
this._rootObj.style.height=this._img.height*this._aspectH+"px";
this._eventObj = this._canvas;
this._cnv=this._canvas.getContext('2d');
var parameters;
while (parameters = this._onLoadDelegate.shift()) {
this._handleRotation(parameters, true);
}
}
})(),
_animateStart:function()
{
if (this._timer) {
clearTimeout(this._timer);
}
this._animateStartTime = +new Date;
this._animateStartAngle = this._angle;
this._animate();
},
_animate:function()
{
var actualTime = +new Date;
var checkEnd = actualTime - this._animateStartTime > this._parameters.duration;
// TODO: Bug for animatedGif for static rotation ? (to test)
if (checkEnd && !this._parameters.animatedGif)
{
clearTimeout(this._timer);
}
else
{
if (this._canvas||this._vimage||this._img) {
var angle = this._parameters.easing(0, actualTime - this._animateStartTime, this._animateStartAngle, this._parameters.animateTo - this._animateStartAngle, this._parameters.duration);
this._rotate((~~(angle*10))/10);
}
if (this._parameters.step) {
this._parameters.step(this._angle);
}
var self = this;
this._timer = setTimeout(function()
{
self._animate.call(self);
}, 10);
}
// To fix Bug that prevents using recursive function in callback I moved this function to back
if (this._parameters.callback && checkEnd){
this._angle = this._parameters.animateTo;
this._rotate(this._angle);
this._parameters.callback.call(this._rootObj);
}
},
_rotate : (function()
{
var rad = Math.PI/180;
if (IE)
return function(angle)
{
this._angle = angle;
this._container.style.rotation=(angle%360)+"deg";
this._vimage.style.top = -(this._rotationCenterY - this._imgHeight/2) + "px";
this._vimage.style.left = -(this._rotationCenterX - this._imgWidth/2) + "px";
this._container.style.top = this._rotationCenterY - this._imgHeight/2 + "px";
this._container.style.left = this._rotationCenterX - this._imgWidth/2 + "px";
}
else if (supportedCSS)
return function(angle){
this._angle = angle;
this._img.style[supportedCSS]="rotate("+(angle%360)+"deg)";
this._img.style[supportedCSSOrigin]=this._parameters.center.join(" ");
}
else
return function(angle)
{
this._angle = angle;
angle=(angle%360)* rad;
// clear canvas
this._canvas.width = this._width;//+this._widthAdd;
this._canvas.height = this._height;//+this._heightAdd;
// REMEMBER: all drawings are read from backwards.. so first function is translate, then rotate, then translate, translate..
this._cnv.translate(this._imgWidth*this._aspectW,this._imgHeight*this._aspectH); // at least center image on screen
this._cnv.translate(this._rotationCenterX,this._rotationCenterY); // we move image back to its orginal
this._cnv.rotate(angle); // rotate image
this._cnv.translate(-this._rotationCenterX,-this._rotationCenterY); // move image to its center, so we can rotate around its center
this._cnv.scale(this._aspectW,this._aspectH); // SCALE - if needed ;)
this._cnv.drawImage(this._img, 0, 0); // First - we draw image
}
})()
}
if (IE)
{
Wilq32.PhotoEffect.prototype.createVMLNode=(function(){
document.createStyleSheet().addRule(".rvml", "behavior:url(#default#VML)");
try {
!document.namespaces.rvml && document.namespaces.add("rvml", "urn:schemas-microsoft-com:vml");
return function (tagName) {
return document.createElement('<rvml:' + tagName + ' class="rvml">');
};
} catch (e) {
return function (tagName) {
return document.createElement('<' + tagName + ' xmlns="urn:schemas-microsoft.com:vml" class="rvml">');
};
}
})();
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment