Creating an Analog Clock with CSS and Javascript
This example, which you can watch the speed code video above, will be a good practice for those who are new to front-end web development. Also here you can find the codes of this example.
As always, we start with HTML tags. We create div
class-named frame
to wrap all other elements. Within this div.frame
we create 3 other elements class-named stick
to all and second minute hour
one for each. This three elements will be our indicator which we will rotate later. Finally a div
with line-wrapper
class and 12 child element with class-named to line
to show numbers and small black bars.
HTML is ready. Let me explain styles. We give equal width and height to frame
element so that we can get a circle with border-radius
also position:relative
is necessary because all child elements will be positioned absolute.
stick
elements have styles which allow us to center elements both vertically and horizontally. As transform-origin
we use bootom center
because we will do the rotary motion using the transform
style and we want the element to rotate while the bottom end remains constant.
The situation is different for the seconds indicator. In real analog clocks, we are making the center of rotation a little bit higher than the second
class, to add the long tail after the seconds indicator. We also give the bottom
value accordingly. Finally we cover the center of rotation by bringing a round element to the center of the clock with second::before
pseudo element. We also provide styles suitable for minute
and hour
classes.
line
elements will be black bars with numbers, line::after
will content numbers. Here, using the nth-child
feature, we can give according rotation values and numbers for each line.
Styling is done, lets move to scripting. We create a self-invoking function and assign it to a variable named clock
Thus, the variables we will use for the clock will be inaccessible in the global scope, and we will not break any variable in the global scope. (see encapsulation). We assign all three of our indicators into variables with document.querySelector
. We create 3 variables in which we keep the degrees of rotation for each seconds, minutes and hours. Every second and minute will rotate the according indicator 6 degrees, and the hour indicator will take a fraction of 0–30 degrees for minutes plus 30 degrees for each hour.
With a function called rotate
, we get the element and degree value as parameters and do the rotation.
We use setInterval
to run the tick
function every second, we update the degree variables and call the rotate function again.