countdown

How to Create an Animated Countdown Timer With HTML, CSS, and JavaScript?

Have you ever needed a countdown timer on an HTML project? For something like that, it might be natural to reach for a plugin, but it’s actually a lot more straightforward to make one than you might think and only requires the HTML, CSS, and JavaScript. This countdown timer is responsive to all devices and supports all browsers.

Also, you have to use Bootstrap.

Moreover, this feature will make your website more attractive and add immense value.

Step 1: HTML Code

<div id="timer" class="flex-wrap d-flex justify-content-center">
    <div id="days" class="align-items-center flex-column d-flex justify-content-center"></div>
    <div id="hours" class="align-items-center flex-column d-flex justify-content-center"></div>
    <div id="minutes" class="align-items-center flex-column d-flex justify-content-center"></div>
    <div id="seconds" class="align-items-center flex-column d-flex justify-content-center"></div>
</div>

Step 2: CSS Code

#timer div {
   background-color: #000000;
   color: #ffffff;
   width: 100px;
   height: 105px;
   border-radius: 5px;
   font-size: 35px;
   font-weight: 700;
   margin-left: 10px;
   margin-right: 10px;
}
#timer div span {
   display: block;
   margin-top: -2px;
   font-size: 15px;
   font-weight: 500;
}

Step 3: JavaScript Code

function makeTimer() {
   var endTime = new Date("September 20, 2021 17:00:00 PDT");
   var endTime = (Date.parse(endTime)) / 1000;
   var now = new Date();
   var now = (Date.parse(now) / 1000);
   var timeLeft = endTime - now;
   var days = Math.floor(timeLeft / 86400); 
   var hours = Math.floor((timeLeft - (days * 86400)) / 3600);
   var minutes = Math.floor((timeLeft - (days * 86400) - (hours * 3600 )) / 60);
   var seconds = Math.floor((timeLeft - (days * 86400) - (hours * 3600) - (minutes * 60)));
   if (hours < "10") { hours = "0" + hours; }
   if (minutes < "10") { minutes = "0" + minutes; }
   if (seconds < "10") { seconds = "0" + seconds; }
   $("#days").html(days + "<span>Days</span>");
   $("#hours").html(hours + "<span>Hours</span>");
   $("#minutes").html(minutes + "<span>Minutes</span>");
   $("#seconds").html(seconds + "<span>Seconds</span>");
}
setInterval(function() { makeTimer(); }, 0);

Step 4: Responsive CSS Code (If Need)

@media only screen and (max-width: 767px) {
   #timer {
     margin-top: -20px;
   }
   #timer div {
     width: 95px;
     height: 100px;
     font-size: 32px;
     margin-top: 20px;
  }
  #timer div span {
    font-size: 14px;
  }
}

2 Comments:

  1. Hello, Which Bootstrap .js file do I need? I have bootstrap.min.js, but it doesn’t show the boxes. Thanks for your help :).

Leave a Reply

Your email address will not be published. Required fields are marked *