User:Bawolff/sandbox/utcclockthingy.js

From Wikinews, the free news source you can write!
Jump to navigation Jump to search

Note: After saving, you may have to bypass your browser's cache to see the changes. Mozilla / Firefox / Safari: hold down Shift while clicking Reload, or press Ctrl-Shift-R (Cmd-Shift-R on Apple Mac); IE: hold Ctrl while clicking Refresh, or press Ctrl-F5; Konqueror: simply click the Reload button, or press F5; Opera users may need to completely clear their cache in Tools→Preferences. — More skins

/*extern getElementsByClassName addOnloadHook*/
/* Purpose: To add live updatable times to pages.

Note everything is prefixed with Bawolff purely to stop name conflicts with other js things (specificly the original utc clock). In the interest of credit where credit
is due, none of this code is really mine, most of it is stolen from other people.

This will find any element with class 'utcautoclock' and go from there. Recomend using wikitext like:

<span class='utcautoclock'>{{CURRENTHOUR}}:{{CURRENTMINUTE}}:{{CURRENTSECOND}}</span>

*/
if (typeof Bawolff === "undefined") {
    var Bawolff = {};
}

Bawolff.LiveClock = function (node) {
/*constructor*/
this.node = node;

}

Bawolff.LiveClock.prototype.showTime = function () {
	var dateNode = this.node;
	if( !dateNode ) {
		return;
	}

        var now = new Date();

	var hh = now.getUTCHours();
	var mm = now.getUTCMinutes();
	var ss = now.getUTCSeconds();
	var time = ( hh < 10 ? '0' + hh : hh ) + ':' + ( mm < 10 ? '0' + mm : mm ) + ':' + ( ss < 10 ? '0' + ss : ss );
	dateNode.replaceChild( document.createTextNode( time ), dateNode.firstChild );

}

Bawolff.LiveClock.prototype.start = function () {
    //weirdness due to interval does function in context of window, so need to change this.
    var that = this;
    var tmp = function () {
       that.showTime();
    }
    window.setInterval(tmp, 1000);


}

Bawolff.LiveClock.init = function () {
    var dateList;
    if (document.getElementsByClassName) { /*HTML5*/
        dateList = document.getElementsByClassName("utcautoclock");
    }
    else { /* inefficient w3c DOM + custom func in wikibits*/
         try {
         dateList = getElementsByClassName(document, '*', 'utcautoclock');
         } catch(e) {}
    }

    var cur;
    for (var i = 0; i < dateList.length;i++) {
        cur = new Bawolff.LiveClock(dateList[i]);
        cur.start();
    }


}


$(Bawolff.LiveClock.init);