In This Article, We will learn How to implement an animated Countdown Through Javascrtip HTML CSS. The User only needs to add the date and timing, then the countdown with a run which will show the days, date, and time once the time is completed we have a function to execute the method after the countdown is over, The number digit has a slide animation in this countdown timer, you can easily implement the countdown timer in your website.
In modern web development, countdown timers are a great way to engage users, highlight upcoming events, or create urgency. This article will explain how to implement a countdown timer functionality using JavaScript, providing both time tracking and smooth animations for a visually appealing experience. We’ll dive into the code, breaking down each section for better understanding.
Demo
Understanding the Countdown Timer Code
Here is the full breakdown of the JavaScript code for the countdown timer functionality:
// Countdown Timer Functionality
function initializeCountdownTimers() {
const timers = document.querySelectorAll(".countdown-timer");
timers.forEach((timer) => {
const dateAttr = timer.getAttribute("data-date");
const timeAttr = timer.getAttribute("data-time") || "00:00:00";
const targetDate = new Date(`${dateAttr}T${timeAttr}`).getTime();
if (isNaN(targetDate)) {
console.error("Invalid date or time in data attributes:", dateAttr, timeAttr);
return;
}
function swapNumbers(element, value, type) {
const current = element.querySelector(`.current.${type}`);
const next = element.querySelector(`.next.${type}`);
// If value hasn't changed, no animation is needed
if (current.textContent === value) return;
// Update the next number and trigger animation
next.textContent = value;
current.classList.add("animate-out");
next.classList.add("animate-in");
// Wait for animation to finish, then swap roles
setTimeout(() => {
current.textContent = value; // Ensure current is updated
current.classList.remove("animate-out");
next.classList.remove("animate-in");
// Swap current and next roles
current.classList.remove("current");
current.classList.add("next");
next.classList.remove("next");
next.classList.add("current");
}, 500);
}
function updateCountdown() {
const now = new Date().getTime();
const difference = targetDate - now;
if (difference <= 0) {
clearInterval(interval);
timer.querySelectorAll(".number-wrapper .current").forEach((span) => (span.textContent = "00"));
alert("Countdown completed!");
return;
}
const days = Math.floor(difference / (1000 * 60 * 60 * 24)).toString().padStart(2, "0");
const hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toString().padStart(2, "0");
const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60)).toString().padStart(2, "0");
const seconds = Math.floor((difference % (1000 * 60)) / 1000).toString().padStart(2, "0");
swapNumbers(timer.querySelector(".days").parentElement, days, "days");
swapNumbers(timer.querySelector(".hours").parentElement, hours, "hours");
swapNumbers(timer.querySelector(".minutes").parentElement, minutes, "minutes");
swapNumbers(timer.querySelector(".seconds").parentElement, seconds, "seconds");
}
// Update every second
const interval = setInterval(updateCountdown, 1000);
updateCountdown(); // Initial call to display the countdown immediately
});
}
// Initialize all countdown timers on page load
document.addEventListener("DOMContentLoaded", initializeCountdownTimers);
Key Components of the Countdown Timer
1. Target Date Setup
The first part of the script grabs the target date and time from the HTML elements using the data-date
and data-time
attributes:
const dateAttr = timer.getAttribute("data-date");
const timeAttr = timer.getAttribute("data-time") || "00:00:00";
const targetDate = new Date(`${dateAttr}T${timeAttr}`).getTime();
data-date
specifies the date for the countdown.
data-time
specifies the time (default is 00:00:00
).
new Date()
creates a JavaScript Date object, and .getTime()
converts it into a timestamp (in milliseconds).
2. Swap Numbers Function
The swapNumbers
function controls the animation of numbers changing on the countdown timer. This function checks whether the number has changed and, if so, triggers an animation for smooth transitions:
function swapNumbers(element, value, type) {
const current = element.querySelector(`.current.${type}`);
const next = element.querySelector(`.next.${type}`);
if (current.textContent === value) return;
next.textContent = value;
current.classList.add("animate-out");
next.classList.add("animate-in");
setTimeout(() => {
current.textContent = value;
current.classList.remove("animate-out");
next.classList.remove("animate-in");
current.classList.remove("current");
current.classList.add("next");
next.classList.remove("next");
next.classList.add("current");
}, 500);
}
This function swaps the numbers and adds/removes animation classes to ensure smooth transitions.
3. Countdown Update Logic
The updateCountdown
function is responsible for calculating the remaining time and updating the timer every second:
function updateCountdown() {
const now = new Date().getTime();
const difference = targetDate - now;
if (difference <= 0) {
clearInterval(interval);
alert("Countdown completed!");
return;
}
const days = Math.floor(difference / (1000 * 60 * 60 * 24)).toString().padStart(2, "0");
const hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toString().padStart(2, "0");
const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60)).toString().padStart(2, "0");
const seconds = Math.floor((difference % (1000 * 60)) / 1000).toString().padStart(2, "0");
swapNumbers(timer.querySelector(".days").parentElement, days, "days");
swapNumbers(timer.querySelector(".hours").parentElement, hours, "hours");
swapNumbers(timer.querySelector(".minutes").parentElement, minutes, "minutes");
swapNumbers(timer.querySelector(".seconds").parentElement, seconds, "seconds");
}
This function calculates the time difference between the target date and the current time, and it updates the countdown timer’s numbers accordingly. If the countdown reaches zero, it stops the timer and alerts the user that the countdown is complete.
4. Automatic Initialization
The script ensures that all countdown timers are initialized when the DOM content is fully loaded:
document.addEventListener("DOMContentLoaded", initializeCountdownTimers);