JAVASCRIPT PROJECT 01

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.

01

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()
02

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>
The id helps JavaScript find and update this element.
03

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;
}
CSS controls the visual appearance of the clock.
04

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();
05

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;
06

Update the Clock Every Second

If the function runs only once, the clock will not continue changing. Therefore, we use setInterval().

setInterval(updateClock, 1000);
1000 milliseconds = 1 second. Therefore, the clock updates once every second.

How the Project Works

HTML Structure
CSS Design
Date Get Time
DOM Update
Interval Repeat
07

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