How to Create a Countdown in JavaScript
In modern web development, countdowns are popular tools used in various scenarios such as limited-time promotions, live events, product launches, and more. Creating a countdown in JavaScript is a straightforward and useful task to enhance the user experience on your website. In this article, I will guide you step-by-step to create a simple countdown using JavaScript.
A countdown timer is a visual tool that counts down from a specific time to zero. Countdown timers can be extremely useful for:
- Showing the remaining time until an event or promotion.
- Creating a sense of urgency for users.
We will build a basic countdown timer using JavaScript, HTML, and CSS. Once completed, you will have a clear understanding of how to implement and customize your own countdown in your web projects.
Basic HTML Structure
Let’s start by creating the basic HTML structure for our countdown timer. We will create a simple container where the countdown will be displayed.
<div class="countdown-timer">
<ul class="countdown-timer-ul">
<p class="deadline-label"><span>May 26, 2025 23:59:59</span></p>
<div class="countainer-ul">
<li class="date-item"><span class="days">0</span>Days</li>
<li class="date-item"><span class="hours">0</span>Hours</li>
<li class="date-item"><span class="minutes">0</span>Minutes</li>
<li class="date-item"><span class="seconds">0</span>Seconds</li>
</div>
</ul>
</div>
Basic CSS Styles
Now we will proceed to style our countdown. For this example, we are applying basic styles to illustrate the functionality, but you can customize the design according to your needs.
.countdown-timer {
animation: fadeIn 2s ease-in-out;
align-items: center;
background-color: #131a2b;
border-radius: 0px;
color: #fff;
font-size: 15px;
font-weight: 600;
padding: 8px;
text-align: left;
text-transform: uppercase;
width: 100%;
}
.countdown-timer .countainer-ul {
display: flex;
justify-content: space-evenly;
}
.countdown-timer-ul {
border-radius: 25px;
color: #000;
margin: auto auto 15px auto;
position: relative;
text-align: center;
transition: opacity 0.7s ease-in-out;
position: relative;
width: 40%;
}
.countdown-timer-ul .deadline-label {
color: #fff;
font-size: 12px;
margin-bottom: 5px;
margin-right: 10%;
text-align: right;
text-transform: uppercase;
}
.countdown-timer .date-item {
background-color: #fafafa52;
border-radius: 5px;
color: #fff;
text-align: center;
font-size: 1.2rem;
width: 88px;
}
.countdown-timer ul {
margin-bottom: 0px;
padding: 0px;
}
.countdown-timer ul li span {
display: block;
font-size: 3rem;
}
li {
display: inline-block;
font-size: 1em;
list-style-type: none;
padding: 0.5em;
text-transform: uppercase;
}
@keyframes fadeIn {
0% {opacity: 0;}
100% {opacity: 1;}
}
Adding Functionality with JavaScript
Lastly, we need to add all the necessary interaction using JavaScript. First, we need to define the date for our countdown (you can handle it as a dynamic date from a database or a static predefined date). From this date, we will get the remaining days, hours, minutes, and seconds.
We need to update the remaining date every second using setInterval
and ensure that if we reach the deadline, we stop this function and, depending on the behavior we need, display an expired message or set the counters to zero.
const expirationDate = 'May 28, 2024 23:59:59'; // Define or get your date
let deadlineTime = new Date(expirationDate);
deadlineTime.setDate(deadlineTime.getDate());
let deadline = deadlineTime.getTime();
// Function to update countdown timer
function updateCountdown() {
if (countdownInterval !== null) {
// Getting current time in required format
let now = new Date().getTime();
let timeToLive = deadline - now;
// Getting value of days, hours, minutes, seconds
let days = Math.floor(timeToLive / (1000 * 60 * 60 * 24));
let hours = Math.floor((timeToLive % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((timeToLive % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((timeToLive % (1000 * 60)) / 1000);
let daysElements = document.getElementsByClassName("days");
let hoursElements = document.getElementsByClassName("hours");
let minutesElements = document.getElementsByClassName("minutes");
let secondsElements = document.getElementsByClassName("seconds");
// If you have many countdowns, you could fill all the tags using the classname
Array.from(daysElements).forEach(el => el.innerHTML = days);
Array.from(hoursElements).forEach(el => el.innerHTML = hours);
Array.from(minutesElements).forEach(el => el.innerHTML = minutes);
Array.from(secondsElements).forEach(el => el.innerHTML = seconds);
// Output for over time
if (timeToLive < 0) {
countdownInterval && clearInterval(countdownInterval);
Array.from(daysElements).forEach(el => el.innerHTML = 0);
Array.from(hoursElements).forEach(el => el.innerHTML = 0);
Array.from(minutesElements).forEach(el => el.innerHTML = 0);
Array.from(secondsElements).forEach(el => el.innerHTML = 0);
}
}
}
// To call defined function every second
let countdownInterval = null;
updateCountdown();
countdownInterval = setInterval(updateCountdown, 1000);
With these changes in the files, we have created our countdown for our website.
Result
Summary
Creating a countdown in JavaScript is a simple but effective task to enhance the user experience on your website. By following the detailed steps in this article, you can implement and customize your own countdown. Here are some final recommendations:
- Customize the Design: Adjust the CSS styles so that the countdown aligns with your website’s design.
- Ensure Accuracy: Verify that the target date and time are correct and perform the necessary tests.
- Optimize Performance: Ensure that the JavaScript code is efficient and does not negatively impact the page’s performance.
With these recommendations in mind, you will be able to create a countdown that is not only functional but also visually appealing and efficient.
Read this story in Spanish: