Master HTML, CSS, and JavaScript by building a digital clock from scratch. A step-by-step guide for beginners to learn coding and web development.
Table of Contents
A digital clock means it shows time in number format. JavaScript receives real-time out of your tool and presentations it at the website. And this post is about how JavaScript gets the time and displays it using some basic methods. Basically, this is a real-time digital clock, which means you can see time in numbers with hours, minutes, and second. And the clock usually works, so you don't need to refresh the website to see the updated time.
Let's start making these amazing responsive navbar with hamburger menu Using HTML, CSS and JavaScript step by step.
Join My Telegram Channel to Download the Project: Click Here
Prerequisites:
Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.
Source Code
Step 1 (HTML Code):
To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our digital clock.
After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.
Let's break down each part of the code:
<!DOCTYPE html>
- This declaration defines the document type and version of HTML (HTML5 in this case).
<html lang="en">
- The opening tag for the HTML document, specifying the language as English.
<head>
- Contains metadata and links to resources such as stylesheets and scripts.
<meta charset="UTF-8">
- Specifies the character encoding for the document, ensuring it supports a wide range of characters.
<meta http-equiv="X-UA-Compatible" content="IE=edge">
- Ensures compatibility with the latest rendering mode of Internet Explorer.
<meta name="viewport" content="width=device-width, initial-scale=1.0">
- Ensures proper scaling on different devices by setting the viewport's width to the device's width and initial scale to 1.
<title>
Digital Clock</title>
- Sets the title of the web page, which appears in the browser tab.
<link rel="stylesheet" href="styles.css">
- Links to an external CSS file named "styles.css" for styling the web page.
<script type="text/javascript" src="script.js">
</script>
- Links to an external JavaScript file named "script.js" for adding interactivity.
<body>
- Contains the main content of the HTML document.
<div class="container">
- A container div to hold all the content related to the digital clock.
<div id="time">
- A div to group all elements related to displaying time.
<div class="circle" style="--color: #ff2972">
- A div with a class "circle" and an inline style setting a custom CSS variable --color to #ff2972. This will affect the color scheme of this clock segment.
<div class="dots h_dot">
</div>
- A div representing hour dots.
<svg>
- An SVG (Scalable Vector Graphics) element used to draw circles.
<circle cx="70" cy="70" r="70">
</circle>
- A circle with a center at (70, 70) and a radius of 70.
<circle cx="70" cy="70" r="70" id="hh">
</circle>
- Another circle with the same center and radius, identified by id="hh", represents the hour hand.
<div id="hours">
00</div>
- A div to display the hour value, initialized to "00".
Similar structures are repeated for minutes and seconds with different colors and ids:
- Minutes: --color: #fee800, id mm, dots class m_dot.
- Seconds: --color: #04fc43, id ss, dots class s_dot.
<div class="ap">
- A div for displaying AM/PM indicator.
<div id="ampm">
AM</div>
- A div to display whether it's AM or PM, initialized to "AM".
This is the basic structure of our digital clock using HTML, and now we can move on to styling it using CSS.
Step 2 (CSS Code):
Once the basic HTML structure of the digital clock is in place, the next step is to add styling to the digital clock using CSS. CSS allows us to control the visual appearance of the clock, including things like layout, color, and typography.
Next, we will create our CSS file. In this file, we will use some basic CSS rules to create our digital clock. We will also add some padding and margin properties to ensure that everything looks correct.
This will give our digital clock an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.
Here's a breakdown of the CSS code:
1. Importing Fonts
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@100;300;400;500;600;700;800;900&display=swap');
- This imports the Poppins font from Google Fonts with various weights. The font will be used throughout the stylesheet for consistency and style.
2. Global Styles
* { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; } *: Targets all elements.
- margin: 0; padding: 0;: Resets margin and padding to zero for all elements to ensure consistent spacing.
- box-sizing: border-box;: Makes sure padding and border are included in the element's total width and height.
- font-family: 'Poppins', sans-serif;: Sets the font for all elements to Poppins, with a fallback to sans-serif.
3. Container Styles
.container { width: 100%; min-height: 100vh; display: flex; justify-content: center; align-items: center; background: #2f363e; }
- .container: Styles a container element.
- width: 100%;: Makes the container span the full width of its parent.
- min-height: 100vh;: Ensures the container is at least the height of the viewport.
- display: flex; justify-content: center; align-items: center;: Uses Flexbox to center content horizontally and vertically.
- background: #2f363e;: Sets a dark background color for the container.
4. Time Section Styles
#time { display: flex; gap: 40px; color: #fff; }
- #time: Styles the element with the ID time.
- display: flex; gap: 40px;: Uses Flexbox to lay out child elements with a 40px gap between them.
- color: #fff;: Sets the text color to white.
5. Circle Styles
#time .circle { position: relative; width: 150px; height: 150px; display: flex; justify-content: center; align-items: center; }
- #time .circle: Styles elements with the class circle inside the time ID.
- position: relative;: Allows for absolutely positioned children within the circle.
- width: 150px; height: 150px;: Sets the dimensions of the circle.
- display: flex; justify-content: center; align-items: center;: Centers content within the circle.
6. SVG Styles
#time .circle svg { position: relative; width: 150px; height: 150px; transform: rotate(270deg); } #time .circle svg circle { width: 100%; height: 100%; fill: transparent; stroke: #191919; stroke-width: 4px; transform: translate(5px, 5px); } #time .circle svg circle:nth-child(2) { stroke: var(--color); stroke-dasharray: 440; }
#time .circle svg: Styles the SVG element within the circle.
- position: relative; width: 150px; height: 150px;: Sets dimensions and relative positioning.
- transform: rotate(270deg);: Rotates the SVG by 270 degrees.
#time .circle svg circle: Styles the circle elements inside the SVG.
- fill: transparent;: Makes the fill color transparent.
- stroke: #191919;: Sets the stroke color to dark gray.
- stroke-width: 4px;: Sets the width of the stroke.
- transform: translate(5px, 5px);: Moves the circle slightly.
#time .circle svg circle:nth-child(2): Targets the second circle in the SVG.
- stroke: var(--color);: Sets the stroke color using a CSS variable.
- stroke-dasharray: 440;: Creates a dashed stroke pattern.
7. Text and Labels
#time div { position: absolute; text-align: center; font-size: 1.5rem; font-weight: 500; } #time div span { position: absolute; transform: translate(-50%, 0px); font-size: 0.5rem; font-weight: 300; letter-spacing: 0.1rem; text-transform: uppercase; } #time .ap { position: relative; font-size: 1rem; transform: translate(-20px); }
#time div: Styles div elements inside the time ID.
- position: absolute;: Positions the text absolutely within the parent container.
- text-align: center;: Centers the text.
- font-size: 1.5rem; font-weight: 500;: Sets the font size and weight.
#time div span: Styles span elements inside div elements within time.
- position: absolute;: Positions the span absolutely within the parent div.
- transform: translate(-50%, 0px);: Centers the span horizontally.
- font-size: 0.5rem; font-weight: 300; letter-spacing: 0.1rem; text-transform: uppercase;: Styles the span text with specific font size, weight, spacing, and transformation.
#time .ap: Styles elements with the class ap within time.
- font-size: 1rem; transform: translate(-20px);: Sets font size and shifts the element horizontally.
8. Dots Styling
.dots { position: absolute; width: 100%; height: 100%; display: flex; justify-content: center; z-index: 10; } .dots::before { content: ''; position: absolute; top: -3px; width: 15px; height: 15px; background: var(--color); border-radius: 50%; box-shadow: 0 0 20px var(--color), 0 0 60px var(--color ); }
.dots: Styles an element with the class dots.
- position: absolute; width: 100%; height: 100%;: Makes it fill its parent container.
- display: flex; justify-content: center;: Centers its children horizontally.
- z-index: 10;: Places it above other elements with a lower z-index.
.dots::before: Adds a pseudo-element before the content of .dots.
- content: '';: Generates empty content.
- position: absolute; top: -3px;: Positions it slightly above the parent.
- width: 15px; height: 15px;: Sets the size of the dot.
- background: var(--color);: Sets the background color using a CSS variable.
- border-radius: 50%;: Makes the dot round.
- box-shadow: 0 0 20px var(--color), 0 0 60px var(--color);: Adds glowing effects around the dot with varying intensities.
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@100;300;400;500;600;700;800;900&display=swap');
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Poppins', sans-serif;
}
.container {
width: 100%;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background: #2f363e;
}
#time {
display: flex;
gap: 40px;
color: #fff;
}
#time .circle {
position: relative;
width: 150px;
height: 150px;
display: flex;
justify-content: center;
align-items: center;
}
#time .circle svg {
position: relative;
width: 150px;
height: 150px;
transform: rotate(270deg);
}
#time .circle svg circle {
width: 100%;
height: 100%;
fill: transparent;
stroke: #191919;
stroke-width: 4px;
transform: translate(5px, 5px);
}
#time .circle svg circle:nth-child(2) {
stroke: var(--color);
stroke-dasharray: 440;
}
#time div {
position: absolute;
text-align: center;
font-size: 1.5rem;
font-weight: 500;
}
#time div span {
position: absolute;
transform: translate(-50%, 0px);
font-size: 0.5rem;
font-weight: 300;
letter-spacing: 0.1rem;
text-transform: uppercase;
}
#time .ap {
position: relative;
font-size: 1rem;
transform: translate(-20px);
}
.dots {
position: absolute;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
z-index: 10;
}
.dots::before {
content: '';
position: absolute;
top: -3px;
width: 15px;
height: 15px;
background: var(--color);
border-radius: 50%;
box-shadow: 0 0 20px var(--color), 0 0 60px var(--color );
}
Step 3 (JavaScript Code):
Finally, we need to make our clock work by adding our JavaScript. Create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document, so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.
Here's an explanation of the JavaScript code
Setting Up the Interval
setInterval(() => {
- setInterval is used to repeatedly execute a function every specified time interval—in this case, every 1000 milliseconds (1 second).
Selecting DOM Elements
let hours = document.getElementById('hours'); let minutes = document.getElementById('minutes'); let secondes = document.getElementById('seconds'); let ampm = document.getElementById('ampm'); let hh = document.getElementById('hh'); let mm = document.getElementById('mm'); let ss = document.getElementById('ss'); let dotH = document.querySelector('.h_dot'); let dotM = document.querySelector('.m_dot'); let dotS = document.querySelector('.s_dot');
- This code selects various DOM elements by their IDs or class names, which will be updated with the current time and visual indicators.
Getting the Current Time
let h = new Date().getHours(); let m = new Date().getMinutes(); let s = new Date().getSeconds(); let ap = h >= 12 ? 'PM' : 'AM';
- new Date().getHours(), new Date().getMinutes(), and new Date().getSeconds() get the current hours, minutes, and seconds from the system clock.
- Determines whether it’s AM or PM based on the hour.
Converting to 12-Hour Format
if (h > 12) { h = h - 12; }
- Converts the hour to a 12-hour format if it's greater than 12 (e.g., 13 becomes 1 PM).
Adding Leading Zeros
h = h < 10 ? '0' + h : h; m = m < 10 ? '0' + m : m; s = s < 10 ? '0' + s : s;
- Ensures single-digit hours, minutes, and seconds are padded with a leading zero (e.g., 5 becomes 05).
Updating Textual Time Display
hours.innerHTML = h + 'Hours'; minutes.innerHTML = m + 'Minutes'; secondes.innerHTML = s + 'Seconds'; ampm.innerHTML = ap;
- Updates the inner HTML of the selected elements to display the current time and period (AM/PM).
Updating Circular Time Indicators
hh.style.strokeDashoffset = 440 - (440 * h) / 12; mm.style.strokeDashoffset = 440 - (440 * m) / 60; ss.style.strokeDashoffset = 440 - (440 * s) / 60;
- Adjusts the strokeDashoffset property of SVG circle elements to create a circular progress effect. This creates a visual representation of hours, minutes, and seconds.
Updating Dot Time Position Indicators
dotH.style.transform = `rotate(${h * 30}deg)`; dotM.style.transform = `rotate(${m * 6}deg)`; dotS.style.transform = `rotate(${s * 6}deg)`;
- Rotates the dots representing hours, minutes, and seconds. Each hour represents 30 degrees (360 degrees / 12 hours), and each minute or second represents 6 degrees (360 degrees / 60 minutes/seconds).
setInterval(() => {
// get time indicator elements
let hours = document.getElementById('hours');
let minutes = document.getElementById('minutes');
let secondes = document.getElementById('seconds');
let ampm = document.getElementById('ampm');
// digits time indicator
let hh = document.getElementById('hh');
let mm = document.getElementById('mm');
let ss = document.getElementById('ss');
// dot time indicator
let dotH = document.querySelector('.h_dot');
let dotM = document.querySelector('.m_dot');
let dotS = document.querySelector('.s_dot');
// get current time
let h = new Date().getHours();
let m = new Date().getMinutes();
let s = new Date().getSeconds();
let ap = h >= 12 ? 'PM' : 'AM';
// convert to 12 hour format
if (h > 12) {
h = h - 12;
}
// add 0 before single digit
h = h < 10 ? '0' + h : h;
m = m < 10 ? '0' + m : m;
s = s < 10 ? '0' + s : s;
// set time and label
hours.innerHTML = h + '
Hours';
minutes.innerHTML = m + '
Minutes';
secondes.innerHTML = s + '
Seconds';
ampm.innerHTML = ap;
// set time circular indicator
hh.style.strokeDashoffset = 440 - (440 * h) / 12;
mm.style.strokeDashoffset = 440 - (440 * m) / 60;
ss.style.strokeDashoffset = 440 - (440 * s) / 60;
// set dot time position indicator
dotH.style.transform = `rotate(${h * 30}deg)`;
dotM.style.transform = `rotate(${m * 6}deg)`;
dotS.style.transform = `rotate(${s * 6}deg)`;
}, 1000);
Final Output:
Conclusion:
In conclusion, we have learned how to build a digital clock from scratch using HTML, CSS, and JavaScript. This project provides a great introduction to web development and helps to reinforce the concepts of HTML, CSS, and JavaScript. To continue your learning journey in web development, consider building more projects and exploring additional resources such as online tutorials and coding bootcamps.
That’s a wrap!
I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.
Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee
And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!
Thanks!
Faraz 😊