Build a Digital Clock
In this project, you will learn how to build a real-time digital clock using HTML, CSS and JavaScript. Follow each step and understand how every part works.
Project Introduction
A digital clock displays the current time on a webpage. JavaScript will read the current system time and update the clock automatically.
Concepts You Will Learn
- HTML elements
- CSS styling
- JavaScript functions
- Date object
- DOM manipulation
- setInterval()
Create the HTML Structure
First, create the area where the time will appear. We will use a div with an id called clock.
<div id="clock">
00:00:00
</div>
Add CSS Styling
Now make the clock look better using CSS. You can change the font size, color, spacing and background.
#clock {
font-size: 60px;
font-weight: bold;
color: #00e5ff;
text-align: center;
}
Get the Current Time
JavaScript provides the Date object to work with dates and times.
const now = new Date();
Now we can get the hours, minutes and seconds.
const hours = now.getHours(); const minutes = now.getMinutes(); const seconds = now.getSeconds();
Update the HTML Using JavaScript
We can use getElementById() to select our clock element.
const clock =
document.getElementById("clock");
Then update its content using textContent.
clock.textContent =
hours + ":" +
minutes + ":" +
seconds;
Update the Clock Every Second
If the function runs only once, the clock will not continue changing. Therefore, we use setInterval().
setInterval(updateClock, 1000);
How the Project Works
Complete Project
You have now learned the main concepts required to build a Digital Clock. Open the complete working project and see the final result.
Digital Clock is Ready! ⏰
Run the complete project and see the live clock.
Run Project Learn JavaScript Date