New to Owl Order Dev? Click here for 2009's best posts!Is it midnight yet? 00:00:00

Sunday, May 30, 2010

Web Gadgets: JavaScript Clock

See the little clock up there? Right above the big red seal? That's a little clock I wrote. Most blogs utilise Flash to implement clocks, but Flash is slow, resource hungry and doesn't work on mobile devices, including iPhones, iPods and iPads.

The clock I wrote, however, is pure JavaScript. Most browsers today have fast JavaScript engines, including mobile browsers, so it's guaranteed to run almost everywhere. It's actually very simple, a few lines of code do the trick.
<span id="clock"></span>
<script type="text/javascript">
update();
function update()
{
var now=new Date();
document.getElementById("clock").innerHTML=
twodigit(now.getHours())
+":"+twodigit(now.getMinutes())
+"<sub>:"+twodigit(now.getSeconds())+"</sub>";
setTimeout("update()",1000-(now.valueOf()%1000));
}
function twodigit(ip)
{
if (ip<10)
return new String("0"+ip);
else
return ip;
}</script>
A little example. This example is hosted on a free webhost, so don't be surprised if it doesn't load. The one on top of this page always loads, though.


I sincerely urge users of Flash-based clock-gadgets to switch to a JavaScript-based one. Feel free to copy the code above and modify it, if you know basic HTML/JavaScript. Note that Blogspot blocks JavaScript codes unless they're in proper HTML/JavaScript gadgets.

No comments:

Post a Comment