XKCD's Now in JS

Updated XKCD's now comic use JS instead of server side code.

by diarmuidie

HTML

<div id="clock">
    <img id="map" src="https://diarmuid.ie/media/10/map.png" alt="Now" title="This image stays roughly in sync with the day (assuming the Earth continues spinning). Shortcut: xkcd.com/now" />
</div>
<p>Images from <a href="https://xkcd.com/1335/">XKCD.com</a>. Code by <a href="https://diarmuid.ie/blog/">Diarmuid.ie</a>

</p>

CSS

#clock {
    background-image: url("https://diarmuid.ie/media/10/clock.png");
    width: 706px;
    height: 705px;
    overflow: hidden;
}

JavaScript

updateMap(); // Initial rotation on load

setInterval(function () {
    updateMap();
}, 30000); // Rotate every 30 sec

function updateMap() {

    todayDate = new Date();
    todayDate.setHours(12, 0, 0, 0); // Time at 12 midday today

    elapsedSec = (Date.now() - todayDate) / 1000; // Seconds since midday

    UTCOffset = todayDate.getTimezoneOffset() * 60; // Calculate USC offset
    
    elapsedPerc = (elapsedSec + UTCOffset) / 86400; // Percentage of the day that has elapsed

    rotateDeg = Math.round(360 * elapsedPerc); // Convert percentage to degree

    // Update Style with browser specific prefixes
    mapElement = document.getElementById("map");
    mapElement.style.webkitTransform = "rotate(" + rotateDeg + "deg)";
    mapElement.style.transform = "rotate(" + rotateDeg + "deg)";
    mapElement.style.MozTransform = "rotate(" + rotateDeg + "deg)";

}