jQuery Color Clock

I noticed a some mentions of The Colour Clock by Jack Hughes in my Google Reader feed. A lot of people seemed to like the idea of the screensaver version of it for the Mac, but were a bit worried about the use of Flash to build the clock. I wanted to try and port The Colour Clock to some good ole’ HTML+JS+CSS. I’ve really been trying to improve my knowledge of jQuery and this seemed like something that would make good practice.

The hardest part was converting the hours, minutes and seconds to hex properly. It could probably be done a lot simpler. The first thing I do is grab the time and map each value from 0 to 255. I also pad each value so it’s always two digits long:

  var time = new Date();
  var hours = time.getHours().toString();

  hours = "00".substr(0, 2 - hours.length) + hours;
  cHours = (255 * hours / 24).toString().split(".")[0];
  pHours = "00".substr(0, 2 - cHours.length) + cHours;

Then I use a JavaScript function to convert those values to hex and make the background color string and throw that all on the page:

  var colour = decToHex(pHours) + decToHex(pMinutes) + decToHex(pSeconds);

  $("#time").html("<a href='#'>" + hours + ":" + minutes + ":" + seconds + "</a>");
  $("#colour").html("<a href='#'>" + colour.substr(0,2) + " " + colour.substr(2,2) + " " + colour.substr(4,2) + "</a>");
  $("body").animate({backgroundColor: "#" + colour}, "slow");

This is all part of a function that gets called when the page is loaded and every second after using the Timer function everyTime():

  $(document).ready(update);
  $(document).everyTime(1000, update, 0);

There’s also an event to move the time and colour elements on and off the screen when you click on them.

  $("#time, #colour").click( function () {
  	if ($("#time").css("top") == "50%") {
  		$("#time").animate({top: "200%", display: "hidden"}, "slow");
  		$("#colour").animate({top: "50%", display: "block"}, "slow");
  	} else {
  		$("#time").animate({top: "50%", display: "block"}, "slow");
  		$("#colour").animate({top: "-100%", display: "hidden"}, "slow");
    }
  });

If you’re at all more curious about how it works then I would really encourage you to dive into the source code. It’s all there, nothing hidden, and the external files that it requires are the Timers and Color jQuery plugins and the Raleway and Droid Sans Mono fonts from the Google Fonts library. You can check it out here. Click the time to see the current hex value. You can even make it into a screensaver by using WebSaver by Sandwich Lab and pointing it here.