Creating a Clock With JavaScript
I have been learning JavaScript and in the course of that I came cross Wes Bos’s JavaScript30 course(https://javascript30.com/). It was highly recommenced in online communities so I thought of following along the course. Of the first few projects, one is “Building a Clock with Vanilla JS, HTML and CSS”.
Here in this article we will go through the steps to do that project.
We will create a clock with JavaScript which takes current time from the JavaScript and it will update its hands based on the current second, minute and hour hand. This article explains about how to build a clock
Knowledge of the following is required
- HTML
- CSS
- JS : JavaScript Classes, Functions, Event Listener
We start by writing our HTML code
We add classes to the HTML code to enable us to style it with CSS and data attributes to target it with javascript.
CSS for clock
3 Hand div in index is used as default. We are going to apply a rotate to each of the hand depending upon on what time it currently is. So Now to turn the hands based on the time, we first need to set the transform-origin because by default the origin from which we transform an element is from the centre(or 50%). All of our hands are positioned in such a way that we want to transform them from the right, so we set transform-origin: 100% and transform: rotate(90deg) to make sure the hands are facing upwards at 12 o’clock.
With our HTML and CSS set up, we have something like this:
JavaScript Code
The three variables here are hourHand, minuteHand and secHand used to target our elements with the data attributes attached to it in the HTML file.
Next thing is to create a class that will hold the function set date().
The set date() function represent the current date. Now variable is assigned to hold the value of current date.
To get the seconds, minutes and hours here’s what you do:
const seconds= now.getSeconds();
const mins= now.getMinutes();
const hour= now.getHours();
Each 60 second prepares minute hand for its next position, and each 60 minutes tick does same for the hour hand.
const minsDegrees = ((mins / 60)
After getting the seconds of the current minute, and in order to get the degrees you should divide the minutes, and hours by 60, 12, respectfully and multiple by each by 360.
const hourDegrees = ((hour / 12) * 360) + ((mins/60)*30) + 90;
It’s a basic percentage calculation. Part divided by whole times 100%, or in this case 360 degrees. We add the 90 degrees because we’ve offset all of the hands 90 degrees to turn them upwards.
We’ll put everything inside a function and run that function in every second. The most common way to do that is with a setInterval with which we call a function every 1000ms.
setInterval(setDate,1000);
Final look
Find the associated code of the article here: https://github.com/madhurima-ms/js_30daysProjects/tree/main/jsclock