Creating a clock using JavaScript
Imagine a clock that shows the time to your users, for example on a travel website with the destination country's time zone? Let’s create this magnificent clock together easily with JavaScript!
Step 1
Let's start with the HTML code.
<div class="clock">
<div class="wrap">
<span class="heure"></span>
<span class="minute"></span>
<span class="seconde"></span>
<span class="dot"></span>
</div>
</div>
.clock
defines the clock, .wrap
defines the background of the clock, .heure
, .minute
, .seconde
are the hands, and .dot
represents the central circle that unites the hands.
Step 2
Let's style the clock and its background.
.clock {
border-radius: 50%;
background: #fff;
border: 5px solid white;
box-shadow: inset 2px 3px 8px 0 rgba(0, 0, 0, 0.1);
}
.wrap {
position: relative;
width: 350px;
height: 350px;
}
Step 3
Let's move on to the hands.
.minute, .heure {
position: absolute;
height: 100px; width: 6px;
margin: auto;
top: -27%; left: 0; bottom: 0; right: 0;
transform-origin: bottom center;
transform: rotate(0deg);
box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.4);
background: black;
}
Step 4
Let's refine the minute hand.
.minute {
position: absolute;
height: 130px;
width: 4px;
top: -38%;
left: 0;
box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.4);
transform: rotate(90deg);
}
After styling the minute and hour hands, we will now style the minute hand more precisely to differentiate them.
Step 5
Let's move on to the second hand.
.seconde {
position: absolute;
height: 90px;
width: 2px;
margin: auto;
top: -26%;
left: 0;
bottom: 0;
right: 0;
border-radius: 4px;
background: #ff4b3e;
transform-origin: bottom center;
transform: rotate(180deg);
}
We will style and make the second hand red.
Step 6
Let's handle the central circle.
.dot {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 12px;
height: 12px;
border-radius: 50%;
background: white;
border: 2px solid #1b1b1b;
border-radius: 50%;
margin: auto;
}
This central circle will serve to unite all the hands at a single point.
Step 7
Let's finish with JavaScript to make our clock functional.
clock();
function clock() {
const date = new Date();
const hours = ((date.getHours() + 11) % 12 + 1);
const minutes = date.getMinutes();
const seconds = date.getSeconds();
const hour = hours * 30;
const minute = minutes * 6;
const second = seconds * 6;
document.querySelector('.heure').style.transform = `rotate(${hour}deg)`;
document.querySelector('.minute').style.transform = `rotate(${minute}deg)`;
document.querySelector('.seconde').style.transform = `rotate(${second}deg)`;
}
setInterval(clock, 1000);