Daylight.js

(Updated November 22, 2011 at 8:20 PM)

You may have noticed that this blog looks a little different after the sun goes down. That’s because I’m field testing Daylight.js, a lightweight JavaScript plugin I wrote last week to calculate a user’s local sunrise and sunset. I’ve put it up on GitHub – my first repository!

You can use it to do all sorts of cool things. In this example – ripped right from the header of this blog – a “night” stylesheet is added to the page if the function night() returns true.

if (night()) {
document.write('<link rel="stylesheet" href="http://number61.net/wp-content/themes/N61/night.css" type="text/css" media="screen" />');
}

Piece of cake. There’s also a day() function that does the same thing, only, well, you know. (You can pop the hood for more fine-grained control, but I’ll leave that as an exercise for the reader.)

Drawbacks

But there’s a drawback: Daylight works by detecting the number of hours between a user’s current time and the time at the prime meridian, so it’s only ballpark-accurate.

Consider this: though both Augusta, ME and Indianapolis, IN are in the Eastern time zone, the sun sets on Augusta about 70 minutes earlier than it does on Indianapolis. Daylight thinks in terms of time zones, so it can’t handle that level of accuracy.

Sure, I could have used the HTML5 geolocation API to determine the user’s exact longitude – by definition, the most accurate measure of the distance between a given location and the prime meridian. That produces an answer that’s good enough for a meteorologist.

But that method has its own drawback: the browser will have to ask the user for permission to use geolocation every time the user visits the site. Daylight is intended to be completely unobtrusive, so that kind of interruption is unacceptable. It would break the illusion of seamlessness. And it would really annoying. So I decided to trade accuracy for friendliness.

So what’s it good for?

Sites like this one. Sites where this sort of functionality is cool, but non-essential. Use your imagination!

Like I said, it’s on GitHub. Give it a whirl if you think it might be useful.

Tagged: ,