DEV Community

Murtaja Ziad
Murtaja Ziad

Posted on • Originally published at blog.murtajaziad.xyz on

How to create a clock using JavaScript?

In the beginning, create a new HTML, CSS & JavaScript file..

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Clock using JavaScript</title>
    <link rel="stylesheet" href="style.css" />
    <script src="app.js" defer></script>
  </head>
  <body></body>
</html>
Enter fullscreen mode Exit fullscreen mode

Then, put a h2 with three span with the ID hours, minutes and seconds..

<h2>
  <span id="hours">00</span> : <span id="minutes">00</span> :
  <span id="seconds">00</span>
</h2>
Enter fullscreen mode Exit fullscreen mode

Now, it will look like this..how to create a clock using javascript 1

Add some basic styling with a background..

body {
  padding: 0;
  margin: 0;
  box-sizing: border-box;

  min-height: 100vh;

  background-image: url("https://images.unsplash.com/photo-1605364441002-c1dbf7d9c7f1?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&q=100");
  background-repeat: no-repeat;
  background-position: center 40%;

  display: flex;
  align-items: center;
  justify-content: center;
}

h2 {
  font-size: 7rem;
  color: white;
}
Enter fullscreen mode Exit fullscreen mode

It will look like this..how to create a clock using javascript 2

After that, create the main function which will get the time and put it into the spans

// Define the hours, minutes & seconds elements.
const hoursEl = document.getElementById("hours");
const minutesEl = document.getElementById("minutes");
const secondsEl = document.getElementById("seconds");

function main() {
  const totalSeconds = new Date().getTime() / 1000;

  const hours = Math.floor(totalSeconds / 3600) % 24;
  const minutes = Math.floor(totalSeconds / 60) % 60;
  const seconds = Math.floor(totalSeconds) % 60;

  hoursEl.innerText = formatTime(hours);
  minutesEl.innerText = formatTime(minutes);
  secondsEl.innerText = formatTime(seconds);
}

// Format the time by adding 0 before the time if it's less than 10..
function formatTime(time) {
  return time < 10 ? `0${time}` : time;
}

// Initial call.
main();

// Call the function every second.
setInterval(main, 1000);
Enter fullscreen mode Exit fullscreen mode

and yeah, now it’s working..how to create a clock using javascript 3

Top comments (0)