Anonymous
Domino 2.0 Rich Internet Applications with IBM Lotus Notes/Domino
You are here: Today » Analog clock in JavaScript
« My JavaScript namespace object explained
Create an HTML table with all the fields in a document »

Analog clock in JavaScript

This is another module of my 'G' namespace. It looks for a div with id 'analog-clock' and fills it with a running clock. The hours are put in position using trigonometry. The three hands are made up of pixels and moved around with JavaScript. The size of the clock and hands, typeface of the hours and colors can be changed using CSS.

The CSS

.clock{position:relative;width:200px;height:200px;border:solid 1px #ccc}
.clock img{width:100%;height:100%}
.clock .face,.clock .face div{position:absolute;top:0;left:0}
.clock .face{font-family:'trebuchet ms';font-size:14px;font-weight:bold}
.clock .hh{background:#f00;width:4px;height:4px}
.clock .mm{background:#00f;width:2px;height:2px}
.clock .ss{background:#0f0;width:1px;height:1px}

The JavaScript

G.clock={
init:function(){var m=this,o=$('analog-clock');if(o)m.prepare(o)},
prepare:function(a){
    var m=this,o=G.create('div',{className:'face'}),r=m.radius=a.offsetWidth/2
    for(i=0;i<12;i++)G.append(o,'div',{innerHTML:i+1})
    m.make('hh',0.5,o);m.make('mm',0.75,o);m.make('ss',0.9,o)
    G.append(a,o);m.setHrs(o,r)
    m.timer=setInterval(G.clock.tick,200)
},
make:function(a,b,c){
    var m=G.clock,n=Math.floor(m.radius*b),o=m[a]=[]
    for(i=0;i<n;i++)o[i]=G.append(c,'div',{className:a})
},
setHrs:function(o,r){
    var p,M=Math,P=M.PI,rp,n=r*0.9
    ;for(i=0;i<12;i++){
        p=o.childNodes[i];rp=(i+1)*2*P/12-P/2
        G.set(p.style,{top:r+M.sin(rp)*n-p.offsetHeight/2+'px',left:r+M.cos(rp)*n-p.offsetWidth/2+'px'})
    }
},
tick:function(){
    var m=G.clock,d=new Date,hh,mm,ss,f=m.update
    try{
        ss=d.getSeconds()+d.getMilliseconds()/1000
        mm=d.getMinutes()+ss/60
        hh=d.getHours()+mm/60
        f(m.hh,hh%12,12);f(m.mm,mm,60);f(m.ss,ss,60)
    }catch(e){alert('error');m.stop()}
},
update:function(a,b,c){
    var M=Math,P=M.PI,rp=b*P*2/c-P/2,r=G.clock.radius
    for(i=0;i<a.length;i++)G.set(a[i].style,{top:r+M.sin(rp)*i+'px',left:r+M.cos(rp)*i+'px'})
},
stop:function(){clearInterval(G.clock.timer)}
}

The HTML

The clock behaviour is triggered by putting this HTML tag in the page:

<div id="analog-clock" class="clock"></div>

Furthermore, you can add an image in the div. If you do so, it is scaled to fill the entire clock and act as a background. You could also put a background using CSS instead.

The result

I've made a new functionality in my blog so that I can enter the custom CSS and JavaScript directly on the page, so you can also check out the source code of this page to see what's happening.

Star rating

69%

Comments

To add a comment, log in or register as new user. It's free and safe.