Scriptless Dynamic SVG

an SVG clock that changes the time shown depending on its document fragment

Last Saturday I was messing around with SVG creating a clock to use to show simple timestamps. I'm not much of an artist so I kept things simple, with a circle and two lines for the arms. I thought it'd be really neat if I could use the same SVG image to show any time. Rotating the arms was easy enough via JS, a little bit of code and everything worked just fine.

I then decided that I'd like to be able to use the SVG image from an <img> tag. SVG isn't allowed to execute scripts when viewed in HTML image tags due to security restrictions. This meant that I couldn't just rotate the arms from JS anymore. I considered setting up a server side script to generate the appropriate clock from query string parameters, but that would be far too easy, and not particularly impressive. Also, the script wouldn't be very portable. I wanted something that I could drop in elsewhere, without needing to rely on a particular server being up.

I started messing with some CSS in the SVG and found that the :target selector works even when the SVG is included via the <img> tag. Problem solved. Instead of passing the time via query string, pass the time via the document fragment, and change which hands are shown by toggling visibility on different elements. I templated out the markup for the hands and generated all 720 positions.

A little bit of CSS, and the hands toggle depending on which is being targeted.

.hands {
    display: none;
}
.hands:target {
    display: block;
}

I also made sure that it showed hands by default when no time was being targeted:

.default {
    display: block;
}
:target ~ .default {
    display: none;
}

At ~150k, it's a much larger file than it needs to be. I'm sure I could have used a different :target technique to handle rotating the arms rather than duplicating the markup so much, but for an unminified first attempt, I feel like it turned out swimmingly.

I threw the source on github. I'm considering adding the hour ticks to the clock frame, and improving the design of the hands, but this will have to do for now. The slider above just changes the hash on the image tag, nothing fancy.