Hey dear web developer, Are you a front-end web developer or are you just learning web development and want to enhance your web development skills further? Then this article will prove helpful for you because, in this article, I am going to teach you step-by-step how you can create an analog clock using HTML CSS and JavaScript.
Along with learning how to make an analog clock, I will provide you with its source code for free. If you already know web development well and you want the source code, you can copy the source code from here.
But I would like to tell you that you should read this article completely and try to make this analog clock by yourself once because after doing this project, you will learn many new JavaScript concepts and you will also learn new properties of CSS.
![Analog Clock using HTML CSS and JavaScript](https://codingprojects.online/wp-content/uploads/2024/01/Analog-Clock-using-HTML-CSS-and-JavaScript.webp)
Algorithm Of Analog Clock Project
Before making the analog clock, we will understand its algorithm because it is very important to understand its algorithm whether the project is easy or complicated.
- Set Up HTML Structure:
- Create an HTML File and write boilerplate code.
- Create a container div for the clock.
- Add elements for the hour, minute, and second hands.
- Add numbers 1 to 12 for the clock face (you can use span tags inside a div tag).
- Style with CSS:
- Define the styles for the clock face, hands, and numbers.
- Use CSS to position and align elements properly.
- JavaScript Initialization:
- JavaScript Initialization:
- Set up a Date object to fetch the current time.
- Fetch Current Time:
- Create a function to fetch the current hour, minute, and second.
- Calculate Rotation Angles:
- Calculate the rotation angle for the hour hand based on the current hour.
- Calculate the rotation angle for the minute hand based on the current minute.
- Calculate the rotation angle for the second hand based on the current second.
- Rotate Hands:
- Use JavaScript to rotate the hour, minute, and second hands according to their respective calculated rotation angles.
- Apply the rotation using CSS transform properties.
- Continuous Update:
- Set an interval to update the clock hands every second.
- Call the rotation function within this interval to ensure continuous movement.
- JavaScript Initialization:
- Deploy:
- You can deploy this project to a Hosting platform and also you can share your code on your GitHub account for public access.
- Don’t forget to share github repo link in our comment box below.
This is the algorithm for our complete Analog Clock project and now we have to convert this algorithm into code. So let’s do it.
Prerequisites to Make an Analog Clock in JavaScript
To create an analog clock project using HTML, CSS, and JavaScript you need:
- Basic knowledge of HTML for structuring the analog clock interface.
- CSS knowledge for styling and layout.
- Basic understanding of JavaScript for handling analog clock logic and updating the display.
- And a code editor for writing and testing code.
Analog Clock HTML Code
Here is the HTML code for the Analog Clock, you can easily understand the code because I have added comments in the code at every step.
And you can also copy the entire code with the “Copy” button.
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta information for character set and viewport -->
<meta charset="UTF-8">
<meta name="viewport" content="width=\, initial-scale=1.0">
<title>Analog Clock Using HTML CSS and JavaScript</title>
<!-- External CSS file for styling the analog clock -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- Container for the analog clock -->
<div class="container">
<!-- Analog clock element with hands and numbers -->
<div class="clock">
<!-- Hour hand element -->
<div style="--clr: #ff3d58; --h: 74px" id="hour" class="hand">
<i></i>
</div>
<!-- Minute hand element -->
<div style="--clr: #00a6ff; --h: 84px" id="min" class="hand">
<i></i>
</div>
<!-- Second hand element -->
<div style="--clr: hsl(145, 83%, 34%); --h: 94px" id="sec" class="hand">
<i></i>
</div>
<!-- Clock numbers placed around the face -->
<span style="--i: 1"><b>1</b></span>
<span style="--i: 2"><b>2</b></span>
<span style="--i: 3"><b>3</b></span>
<span style="--i: 4"><b>4</b></span>
<span style="--i: 5"><b>5</b></span>
<span style="--i: 6"><b>6</b></span>
<span style="--i: 7"><b>7</b></span>
<span style="--i: 8"><b>8</b></span>
<span style="--i: 9"><b>9</b></span>
<span style="--i: 10"><b>10</b></span>
<span style="--i: 11"><b>11</b></span>
<span style="--i: 12"><b>12</b></span>
</div>
</div>
</body>
<!-- External JavaScript code file for analog clock functionality -->
<script src="script.js"></script>
</html>
HTMLThis was a simple HTML code for our analog clock, hope you understand.
Analog Clock Toggle CSS Code
Here is the CSS code for the analog clock toggle, you can easily understand the code because I have added comments in the code at every step.
/* Global reset and base styles */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: sans-serif;
color: #ffffff;
}
/* Styling the body with a radial gradient background */
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: radial-gradient(black, transparent);
}
/* Container styling */
.container {
position: relative;
}
/* Clock styling with dimensions and appearance */
.clock {
width: 300px;
height: 300px;
border-radius: 50%;
background-color: rgba(255, 255, 255, 0.1);
border: 2px solid rgba(255, 255, 255, 0.25);
box-shadow: 0px 0px 30px rgba(0, 0, 0, 0.9);
display: flex;
justify-content: center;
align-items: center;
}
/* Styling for clock numbers */
.clock span {
position: absolute;
transform: rotate(calc(30deg * var(--i)));
inset: 12px;
text-align: center;
}
/* Styling for clock number labels */
.clock span b {
transform: rotate(calc(-30deg * var(--i)));
display: inline-block;
font-size: 20px;
}
/* Styling for clock center dot */
.clock::before {
content: '';
position: absolute;
width: 8px;
height: 8px;
border-radius: 50%;
background-color: #fff;
z-index: 2;
}
/* Styling for clock hands */
.hand {
position: absolute;
display: flex;
justify-content: center;
align-items: flex-end;
}
/* Styling individual clock hands */
.hand i {
position: absolute;
background-color: var(--clr);
width: 4px;
height: var(--h);
border-radius: 8px;
}
CSSHere is the explanation of our CSS code:
- Global Reset & Base Styles:
margin
,padding
,box-sizing
: Resets default spacing and box model for the perfect layout.font-family
: Sets a default sans-serif font for text elements.color
: Defines the default text color as white for elements.
- Body Styling:
display: flex
: Aligns content both horizontally (justify-content
) and vertically (align-items
) in the center.background: radial-gradient
: Creates a background using a radial gradient from black to transparent.
- Clock Design:
width
,height
: Sets width and height of the clock face to 300px by 300px.border-radius
: Gives the clock a circular shape by rounding its corners.background-color
: Adds a white bg color.box-shadow
: Adds a shadow to our clock.
- Clock Numbers & Labels:
position: absolute
: Places numbers around the clock face using absolute positioning.transform: rotate
: Rotates each number to align them evenly around the clock.font-size
: Specifies a font size of 20px for better readability.
- Clock Center Dot:
content
: Adds an empty content area for styling purposes.width
,height
: Sets dimensions for the center dot.border-radius
: Creates a circular shape for the dot.background-color
: Sets the color of the dot to white for contrast.
- Clock Hands Styling:
position: absolute
: Positions the hands relative to the clock face.display: flex
: Using flexbox to align hands centrally and create a pivot effect.background-color
: Sets hand colors using CSS variables (--clr
).width
,height
: Sets width and height for each hand.
Analog Clock JavasScript Code
Here is our JavaScript code for the analog clock functionality using JavaScript. You can easily understand the code because I have added comments at each step.
// Get references to the hour, minute, and second hands
let hr = document.getElementById('hour');
let min = document.getElementById('min');
let sec = document.getElementById('sec');
// Function to update the clock hands based on current time
function displayTime() {
// Create a new Date object to get current time
let date = new Date();
// Extract hours, minutes, and seconds from the date object
let hh = date.getHours();
let mm = date.getMinutes();
let ss = date.getSeconds();
// Calculate rotation angles for each hand based on current time
let hRotation = 30 * hh + mm / 2;
let mRotation = 6 * mm;
let sRotation = 6 * ss;
// Apply rotation transformations to Update the transform property of each clock hand to reflect the calculated rotation angles
hr.style.transform = `rotate(${hRotation}deg)`;
min.style.transform = `rotate(${mRotation}deg)`;
sec.style.transform = `rotate(${sRotation}deg)`;
}
// Set an interval to update the clock every second by calling the displayTime function
setInterval(displayTime, 1000);
JavaScriptExplanation of Analog Clock Toggle’s JavaScript code:
- Clock Hands Setup:
- First of all, get references to the clock hands on the HTML page using their IDs.
- Time Display Function:
- Create a function called
displayTime
to manage the clock’s all functionality.
- Create a function called
- Time Extraction:
- Inside the
displayTime
function, first of all, I set up a Date Object for fetching the current time. - And then from the current date, I extract hours, minutes, and seconds.
- Inside the
- Rotation Angle Calculation:
- Calculate the rotation angles for the clock hands based on the extracted time.
- Hour hand: 30 degrees per hour plus half a degree per minute.
- Minute hand: 6 degrees per minute.
- Second hand: 6 degrees per second.
- Calculate the rotation angles for the clock hands based on the extracted time.
- Update Clock Hands:
- Update the rotation angles for the clock hands’ positions.
- Rotate the hour hand, minute hand, and second hand accordingly.
- Update the rotation angles for the clock hands’ positions.
- Continuous Updating:
- Set up the setInterval an inbuilt function to call the
displayTime
function at every second (1000 milliseconds).
- Set up the setInterval an inbuilt function to call the
Understanding JavaScript Methods and Terms Used in Our Code:
Let’s understand the JavaScript methods and terms used in our code:
document.getElementById()
Method: Used to get references to HTML elements by their IDs, such as ‘hour’, ‘min’, and ‘sec’.Date
Object: Creates a new Date object to fetch the current time.date.getHours()
&date.getMinutes()
&date.getSeconds()
: Used to extract Hours, Minutes, and Seconds from current time.setInterval()
Method: This method is used for repeatedly calling thedisplayTime
function at regular intervals (1000 milliseconds or 1 second).style.transform
Property: This property is used to update the rotation of clock hands dynamically.
So, these all are the functions and methods which is used in our JavaScript code to make an analog clock in JavaScript.
Read this: Dark Mode Toggle using HTML CSS and JavaScript
Read this: How To Create Digital Clock Using HTML CSS and Javascript
Read this: Image Slider using HTML CSS and JavaScript
Read this: Make A Random Quote Generator Using HTML, CSS, and JavaScript
Read this: ToDo List App in JavaScript for Beginners
Conclusion
In this article, you learned how we can create an analog clock using HTML CSS and JavaScript. This was a beginner-friendly project and I hope you have understood it properly.
My only request to you is that you must create this project yourself once and upload it on GitHub and after uploading, please share the link of the repository in the comment box so that me and other readers can check what type of analog clock you have made.
If you are facing any problem or error while making the analog clock then you can comment in the comment box given below, I will try to reply to you as soon as possible.☺️
In the previous article, I taught you how you can make a digital clock using JavaScript. I hope you have read that article but if you have not read it then you can read it by clicking here (Digital Clock).
Thanks 😊.