New to Owl Order? Click here for 2009's best posts! 00:00:00

Friday, 9 July 2010

Web Gadgets: JavaScript Analogue Clock

Last time, I shared a JavaScript clock, mainly as a suggestion to replace the widely used Flash-based clocks.

Today, I'm sharing yet another clock I wrote, but this time, it's the needle-based analogue clock, not the much-simpler-and-lamer number-based digital one.

As usual, feel free to copy the code below and use it. Remember, blogger only allows JavaScript in proper "HTML/JavaScript" gadgets, so this gadget will not work in regular blogposts.
<style type="text/css">
.dot {position:absolute;font-weight:bold;}
.sec {position:absolute;opacity:0.4;font-weight:bold;}
</style>
<div style="position:relative;margin-left:auto;margin-right:auto;width:160px;height:180px;" id="labelcontainer">
<span style="position:absolute;top:80px;left:80px;font-weight:bold;">.</span></div>
<script type="text/javascript">
for (var i=1;i!=8;i++)
{
document.getElementById('labelcontainer').innerHTML+="<span id='hr"+i+"' class='dot'>.</span>";
}
for (var i=1;i!=14;i++)
{
document.getElementById('labelcontainer').innerHTML+="<span id='min"+i+"' class='dot'>.</span>";
}
for (var i=1;i!=3;i++)
{
document.getElementById('labelcontainer').innerHTML+="<span id='sec"+i+"' class='sec'>.</span>";
}
for (var i=1;i!=13;i++)
{
document.getElementById('labelcontainer').innerHTML+="<span class='dot' style='font-weight:bold;opacity:0.4;top:"+y_coor(i*5,80,80)+"px;left:"+x_coor(i*5,80,80)+"px;'>."+"</span>";
}
updatesec();
updatemin();

function updatesec()
{
var now=new Date();
setTimeout('updatesec()',1000-now.valueOf()%1000);
for (var i=1;i!=3;i++)
{
document.getElementById('sec'+i).setAttribute('style','left:'+x_coor(now.getSeconds(),80-i*5,80)+'px;top:'+y_coor(now.getSeconds(),80-i*5,80)+'px;');
}
}

function updatemin()
{
var now=new Date();
setTimeout('updatemin()',60000-now.valueOf()%60000+Math.floor(Math.random()*60));
for (var i=1;i!=14;i++)
{
document.getElementById('min'+i).setAttribute('style','left:'+x_coor(now.getMinutes(),70-i*5,80)+'px;top:'+y_coor(now.getMinutes(),70-i*5,80)+'px;');
}
for (var i=1;i!=8;i++)
{
document.getElementById('hr'+i).setAttribute('style','left:'+x_coor(now.getHours()*5+now.getMinutes()/12,40-i*5,80)+'px;top:'+y_coor(now.getHours()*5+now.getMinutes()/12,40-i*5,80)+'px;');
}
}

function x_coor(sec,radius,offset)
{
return (Math.sin(sec*0.10472)*radius+offset);
}

function y_coor(sec,radius,offset)
{
return (offset-Math.cos(sec*0.10472)*radius);
}
</script>
And a sample for you!

Note that this clock contains no image -- the only thing used is the period character (AKA full-stop). And oh, it may not work on Internet Explorer (unless you have IE9 or newer), so try using a third party browser like Mozilla Firefox instead.

Have fun with it!

No comments:

Post a Comment

Note: only a member of this blog may post a comment.