Countdown Timer with HTML, CSS & JavaScript | Plantpot

Countdown Timer with HTML, CSS & JavaScript

Web Dev
Sponsored links

Demo

Full Screen

 

Sponsored links

 

Video

YouTube Channel

 

Sponsored links

 

Code

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Countdown Timer with HTML, CSS & JavaScript</title>
    <link rel="stylesheet" type="text/css" href="style.css">
  </head>
  <body>
    <div class="time-container">
      <div class="time"><p>Days</p><span id="days">00</span></div>
      <div class="time"><p>Hours</p><span id="hours">00</span></div>
      <div class="time"><p>Minutes</p><span id="minutes">00</span></div>
      <div class="time"><p>Seconds</p><span id="seconds">00</span></div>
    </div>
    <script src="timer.js"></script>
  </body>
</html>

CSS

@charset "utf-8";
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@500&display=swap');
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
html {
  font-family: 'Roboto', sans-serif;
  font-size: 16px;
}
body {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  background-color: #03031b;
}
.time-container {
  display: flex;
  justify-content: center;
}
.time {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin: 0 15px;
  color: #fff;
  font-size: 1rem;
}
.time span {
  margin-top: 10px;
  color: #fac984;
  font-size: 3rem;
}
@media screen and (max-width: 480px) {
  .time {
    font-size: 0.875rem;
    margin: 0 8px;
  }
  .time span {
    font-size: 1.75rem;
  }
}

JavaScript

function countDown() {
  const now = new Date();
  const targetTime = new Date(`January 1, ${now.getFullYear() + 1} 00:00:00`);

  const diff = targetTime - now;

  const d = Math.floor(diff / (24 * 60 * 60 * 1000));
  const h = Math.floor(diff / (60 * 60 * 1000)) % 24;
  const m = Math.floor(diff / (60 * 1000)) % 60;
  const s = Math.floor(diff / 1000) % 60;

  document.getElementById('days').innerHTML = d;
  document.getElementById('hours').innerHTML = ("0" + h).slice(-2);
  document.getElementById('minutes').innerHTML = ("0" + m).slice(-2);
  document.getElementById('seconds').innerHTML = ("0" + s).slice(-2);
}

setInterval(countDown, 1000);