The premise of the program is to have an analogic clock with seconds, minutes and hour hands. These hands will point to the current time.
Before writing any code, we need to get an idea of the actual steps to take to go from nothing to finished product.
In this project the use of JavaScript and CSS are equally important as they both need to work together for the clock to work well.
First, let's create the setup. We'll create index.html, which will just be a regular HTML skeleton putting in JS and CSS.
We'll add some style here, just for the app to make sense and look nice:
We need to style the hands of the clock by adding some transform and transition properties to them:
Let's get started with the JavaScript now! We need to add a setInterval()
method to set the movement of the hands by second. As parameter we will add a function setDate()
(we're gonna create this in the next step), and the interval in milliseconds (in this case 1 second because that's the base unit of time):
Let's now create the setDate()
function using ES6 syntax. Then we need to create a constant that sets the current date time for seconds, minutes and hour. To do this we can use the new Date()
method:
And then get the seconds, minutes and hour from const now
with the following methods:
Let's start with the second hand. We need it to rotate following the degrees at which the seconds stand. We can use a simple math formula: (current seconds / 60) * 360. Let's translate this into JavaScript code:
Now, we have a problem here. Since we previously transformed all clock hands by rotating them by 90 degrees, we need to add 90 to the math formula, otherwise the clock would not be exact on displaying the current seconds:
Then we can query select the second, minutes and hour hands as we'll later need to apply the transform style to them:
Now that we queried the HTML elements that represent the hands, we can use the style.transform
property to rotate the elements to the desiered degrees:
Hurray! We got the second hand moving. Now let's do the same for the minutes and the hour hands:
Now, there's a small improvement here we can make about the clock hands. We want the minutes and hour hands to progressively move with the passing of the seconds/minutes, to make the clock look more real. We can improve the formulas in this way:
Here we have the final script.js file: