User:Caburum/UTCclock.js

Source: Wikipedia, the free encyclopedia.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// UTCclock
// Adds a clock displaying the current UTC time
// Based on https://dev.fandom.com/wiki/MediaWiki:DisplayTimer/code.js

(function ($, mw) {
	'use strict';

	var clockNode;
	var updateClockInterval;

	function updateClock() {
		clockNode.textContent = new Date().toUTCString().slice(5, -3) + '(UTC)';
	}

	function stopClock(cancel) {
		if (cancel || clockNode.isConnected === false) {
			document.removeEventListener('visibilitychange', startClock);
		}

		clearInterval(updateClockInterval);
	}

	function startClock() {
		stopClock();

		if (document.visibilityState === 'visible') {
			updateClock();
			updateClockInterval = setInterval(updateClock, 1000);
		}
	}

	function main() {
		var $clock = $('<li>').attr('id', 'UTCclock').css('direction', 'ltr');
		clockNode = $clock[0];

		$(document.querySelectorAll('#UTCclock')).remove();

		switch (mw.config.get('skin')) {
			case 'timeless': $clock.appendTo('#site-tools ul'); break;
			case 'minerva': $('<ul>', {class: 'hlist', id: 'UTCclock', css: {'padding-left': '12px'}}).insertBefore('.navigation-drawer .menu > ul:last').append($clock); break;
			case 'vector': case 'monobook': default: $clock.prependTo('#p-personal ul'); break;
		}

		startClock();
		document.addEventListener('visibilitychange', startClock);
	}

	$(main);
}(jQuery, mediaWiki));