A real-time clock is a very useful element for websites where time is the primary concern. The clock can display world time or local time in the clock as per needs. The clocks are basically two types, analog and digital. This tutorial will explain how to build an analog clock using JavaScript and CSS.
In this example real-time analog clock, three hands will be used to indicate hours, minutes, and seconds. You can use custom images of the clock dial and hands to match with the web page UI. There are various jQuery plugins are available to build an analog clock. If you want to create your own analog clock with custom images, this step-by-step guide helps you to build a real-time analog clock with pure JavaScript and CSS.
Create a basic structure of the clock using HTML.
<div class="clock">
<div class="h-hand" id="hour"> </div>
<div class="m-hand" id="min"> </div>
<div class="s-hand" id="sec"> </div>
</div>
JavaScript helps to build logic for the rotation of the clock hands.
function clockInit(){
var date = new Date();
var time = [date.getHours(), date.getMinutes(), date.getSeconds()];
var clockDivs = [document.getElementById("hour"), document.getElementById("min"), document.getElementById("sec")];
var hour = time[1]/2+time[0]*30;
clockDivs[0].style.transform="rotate("+ hour +"deg)";
clockDivs[1].style.transform="rotate("+ time[1]*6 +"deg)";
clockDivs[2].style.transform="rotate("+ time[2]*6 +"deg)";
}
Now, call the clockInit()
function on page load.
window.onload = function() {
// Load clockInit function
clockInit();
// Call clockInit function at 1 second interval
setInterval(clockInit, 1000);
};
The CSS is used to design the clock dial and hands.
.clock {
position: relative;
background-image: url('images/e-clock.png');
width: 500px;
height: 500px;
background-size: contain;
}
.h-hand {
position: absolute;
left: 238px;
top: 154px;
background-image: url('images/hour.png');
height: 105px;
width: 27px;
background-size: 27px 105px;
transform-origin: 50% 95%;
}
.m-hand {
position: absolute;
left: 240px;
top: 80px;
background-image: url('images/min.png');
height: 180px;
width: 20px;
background-size: 20px 180px;
transform-origin: 50% 95%;
}
.s-hand {
position: absolute;
left: 237px;
top: 80px;
background-image: url('images/sec-e.png');
height: 180px;
width: 30px;
background-size: 30px 180px;
transform-origin: 45% 95%;
}
Create Simple Modal Popup using JavaScript and CSS
We hope this simple analog clock script will help you to create an analog clock in JavaScript. Use this code snippet to build a real-time analog clock with JavaScript using HTML and CSS. You can customize the analog clock by using custom images for clock dial and hour/minute/second hands.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request