JavaScript Clocks
Earlier this year, I created a JavaScript analogue clock for a side-project. The clock never made it into shipping code, so I thought I’d share it here for posterity.
The HTML is more complex than I might like:
<div class="clock-container">
<div class="clock-body">
<div class="clock-hours"></div>
<div class="clock-center-shadow"></div>
<div class="clock-minutes"></div>
<div class="clock-center"></div>
<div class="clock-seconds"></div>
<div class="clock-center-seconds"></div>
</div>
</div>
And, as always, the CSS is incredibly verbose:
.clock-container {
background: #324B72;
padding: 32px 0;
margin: 0;
border-radius: 6px;
text-align: center;
}
.clock-body {
display: inline-block;
position: relative;
height: 200px;
width: 200px;
border: 8px solid #fff;
border-radius: 50%;
box-shadow:
0 0 5px rgba(0, 0, 0, 0.3),
inset 0 0 5px rgba(0, 0, 0, 0.3);
margin: 8px;
}
.clock-type-night {
background-color: rgba(0, 0, 0, 0.3);
}
.clock-type-day {
background-color: rgba(255, 255, 255, 0.3);
}
.clock-hours {
box-sizing: border-box;
background-color: #fff;
position: absolute;
width: 8px;
height: 50px;
border-radius: 4px;
bottom: 96px;
left: 96px;
transform-origin: 4px 46px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}
.clock-minutes {
box-sizing: border-box;
background-color: #fff;
position: absolute;
width: 6px;
height: 80px;
border-radius: 4px;
bottom: 97px;
left: 97px;
transform-origin: 3px 77px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}
.clock-center-shadow {
position: absolute;
width: 18px;
height: 18px;
background-color: #fff;
border-radius: 50%;
left: 91px;
top: 91px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}
.clock-center {
position: absolute;
width: 18px;
height: 18px;
background-color: #fff;
border-radius: 50%;
left: 91px;
top: 91px;
}
.clock-seconds {
box-sizing: border-box;
background-color: #aaa;
position: absolute;
width: 2px;
height: 100px;
border-radius: 4px;
bottom: 89px;
left: 99px;
transform-origin: 1px 89px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}
.clock-center-seconds {
position: absolute;
width: 8px;
height: 8px;
background-color: #aaa;
border-radius: 50%;
left: 96px;
top: 96px;
}
But at least the JavaScript is fairly simple:
$(document).ready(function() {
var transform = function(degrees) {
return "rotate(" + degrees + "deg)";
}
var updateTime = function() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var hourDegrees = (hours * 30) + (minutes * 0.5);
var minuteDegrees = ((minutes * 60) + seconds) * 0.1;
var secondDegrees = (seconds * 6);
$('.clock-hours').css("transform", transform(hourDegrees));
$('.clock-minutes').css("transform", transform(minuteDegrees));
$('.clock-seconds').css("transform", transform(secondDegrees));
};
setInterval(updateTime, 1000);
updateTime();
});