
To learn how to create the Countdown Timer follow the steps below:
Demo:
Step1.
Add HTML
<div class="countdown-container">
<h1 id="christmasTime">Let's countdown to Christmas!</h1>
<div id="countdown">
<ul>
<li><span id="d"></span>Days</li>
<li><span id="hr"></span>Hours</li>
<li><span id="min"></span>Minutes</li>
<li><span id="sec"></span>Seconds</li>
</ul>
</div>
<div id="fest" class="emoji">
<span>🎄</span>
<span>🎅</span>
<span>🎁</span>
</div>
</div>
Step2.
Add CSS
Set the colour and the position of the background and elements:
body {
background-color: #006d77;
justify-content: center;
align-items: center;
display: flex;
height: 100vh;
}
Style the countdown container:
.countdown-container {
position: relative;
color: white;
}
h1 {
letter-spacing:7px;
}
li {
display: inline-block;
font-size: 20px;
list-style-type: none;
padding: 35px;
text-align: center;
}
li span {
display: block;
font-size: 4.5rem;
}
.emoji {
display: none;
padding: 35px;
}
.emoji span {
font-size: 4rem;
padding: 20px;
}
Add @media rule (to display on small screen devices):
@media only screen and (max-width: 450px) {
h1 {
font-size: 30px;
}
li {
font-size: 30px;
padding: 20px;
text-align: center;
}
li span {
font-size: 30px;
}
}
Step3.
Add JavaScript
(function () {
const sec = 1000,
min = sec * 60,
hr = min * 60,
d = hr * 24;
let christmas = "Dec 24, 2022 00:00:00",
countDown = new Date(christmas).getTime(),
x = setInterval(function() {
let now = new Date().getTime(),
distance = countDown - now;
document.getElementById("d").innerText = Math.floor(distance / (d)),
document.getElementById("hr").innerText = Math.floor((distance % (d)) / (hr)),
document.getElementById("min").innerText = Math.floor((distance % (hr)) / (min)),
document.getElementById("sec").innerText = Math.floor((distance % (min)) / sec);
if (distance < 0) {
let christmasTime = document.getElementById("christmasTime"),
countdown = document.getElementById("countdown"),
fest = document.getElementById("fest");
christmasTime.innerText = "Happy Christmas!";
countdown.style.display = "none";
fest.style.display = "block";
clearInterval(x);
}
}, 0)
}());
Enjoy coding!
Read also:
CSS & JavaScript Digital Clock