How to create a countdown with Tailwind CSS and JavaScript

RMAG news

Let’s recreate the countdown timer from the tutorial with Alpine.js but with vainilla JavaScript.
See it live and get the code

Some background on countdown timers

A countdown timer is a way to display the remaining time until a certain event or deadline. It’s a great way to showcase the urgency of an event or to give people a sense of time left.

Uses cases:

Events: Countdown timers serve as visual aids, displaying the remaining time until an event or deadline, whether it’s a social gathering, business conference, or project milestone. They help participants stay informed and prepared.

Reminders: Countdown timers function as handy reminders, notifying individuals of impending events or deadlines. They’re particularly useful for ensuring timely preparation and attendance.

Timers: Countdown timers act as digital clocks ticking down to specific events or deadlines. They aid in time management by providing a clear indication of how much time remains until a scheduled occurrence.

Countdowns: Countdown timers create anticipation and excitement leading up to significant events, like product launches, sales, or holidays. They build suspense and engagement among audiences, enhancing the overall experience.

Deadlines: Countdown timers are invaluable tools in professional environments, helping teams track and manage project deadlines. By visually representing the time remaining until a task must be completed, they foster accountability and encourage productivity.

Sales Promotions: Countdown timers can be utilized in marketing campaigns to create a sense of urgency and encourage immediate action, such as limited-time offers or flash sales.

Fitness and Training: Countdown timers are useful for timing exercise intervals, rest periods, or workout sessions, aiding in structured fitness routines and improving performance.

Online Auctions: Countdown timers are essential in online auction platforms to display the time remaining for bidding on items, fostering competitiveness and driving engagement.

Cooking and Baking: Countdown timers help chefs and home cooks keep track of cooking durations, ensuring dishes are prepared to perfection and preventing overcooking.

Travel Planning: Countdown timers assist travelers in counting down to their upcoming trips or vacations, allowing them to stay organized and excited about their upcoming adventures.

Education and Study Sessions: Countdown timers can be employed by students to allocate specific time periods for studying, revising, or completing assignments, enhancing productivity and focus.

Medical and Healthcare: Countdown timers are beneficial in medical settings for timing medication doses, treatment durations, or patient monitoring intervals, ensuring adherence to protocols and schedules.

The tiny structure

This is the structure of the project:
Understanding the code:

id=”countdown”: This is the id of the container element that will hold the countdown timer. JavaScript will use this id to target the element and inject the countdown timer.

Classes are omited for brevity and clarity.

<div
id=“countdown”
class=“…”>
</div>

The JavaScript

document.addEventListener(“DOMContentLoaded”, () => {: This is the event listener that will be triggered when the DOM is fully loaded.

const countdownContainer = document.getElementById(“countdown”);: This is the variable that will be used to target the countdown container element.

const endDate = new Date(“2024-12-31T23:59:59”).getTime();: This is the variable that will be used to store the end date of the countdown timer.

Formatting the remaining time

function formatTime(time) {: This is the function that will be used to format the remaining time.

const days = Math.floor(time / (1000 * 60 * 60 * 24));: This is the calculation that will be used to determine the number of days remaining.

const hours = Math.floor((time % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));: This is the calculation that will be used to determine the number of hours remaining.

const minutes = Math.floor((time % (1000 * 60 * 60)) / (1000 * 60));: This is the calculation that will be used to determine the number of minutes remaining.

const seconds = Math.floor((time % (1000 * 60)) / 1000);: This is the calculation that will be used to determine the number of seconds remaining.

return { days, hours, minutes, seconds };: This is the return statement that will be used to return the formatted time.

Creating the countdown elements

function createCountdownElement(value, label) {: This is the function that will be used to create the countdown elements.

return: This is the return statement that will be used to return the countdown element.
This is the template for the countdown element:

<div class=“countdown-item …”>
<div class=“countdown-value …”>${value}</div>
<div class=“countdown-label …”>${label}</div>
</div>

Updating the countdown

function updateCountdown() {: This is the function that will be used to update the countdown.

const now = new Date().getTime();: This is the variable that will be used to store the current time.

const remainingTime = Math.max(0, endDate – now);: This is the variable that will be used to store the remaining time until the end date.

const {days, hours, minutes, seconds} = formatTime(remainingTime);: This is the variable that will be used to store the formatted time remaining.

countdownContainer.innerHTML = remainingTime > 0 ?: This is the conditional statement that will be used to determine whether to display the countdown elements or not.

createCountdownElement(days, “Days”): This is the function call that will be used to create the days countdown element.

createCountdownElement(hours, “Hours”): This is the function call that will be used to create the hours countdown element.

createCountdownElement(minutes, “Minutes”): This is the function call that will be used to create the minutes countdown element.

createCountdownElement(seconds, “Seconds”): This is the function call that will be used to create the seconds countdown element.

<div class=”…”><div class=”…”>Countdown has ended!</div></div>: This is the string that will be used to display the countdown has ended message

: createCountdownElement(0, “Seconds”): This is the function call that will be used to create the seconds countdown element.

The final code:

document.addEventListener(DOMContentLoaded, () => {
const countdownContainer = document.getElementById(countdown);
const endDate = new Date(2024-12-31T23:59:59).getTime();

function formatTime(time) {
const days = Math.floor(time / (1000 * 60 * 60 * 24));
const hours = Math.floor(
(time % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
);
const minutes = Math.floor((time % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((time % (1000 * 60)) / 1000);
return {
days,
hours,
minutes,
seconds
};
}

function createCountdownElement(value, label) {
return `
<div class=”countdown-item …”>
<div class=”countdown-value …”>
${value}</div>
<div class=”countdown-label …”>
${label}</div>
</div>
`
;
}

function updateCountdown() {
const now = new Date().getTime();
const remainingTime = Math.max(0, endDate now);
const {
days,
hours,
minutes,
seconds
} = formatTime(remainingTime);

countdownContainer.innerHTML =
remainingTime > 0 ?
createCountdownElement(days, Days) +
createCountdownElement(hours, Hours) +
createCountdownElement(minutes, Minutes) +
createCountdownElement(seconds, Seconds) :
`<div class=”…”><div class=”…”>Countdown has ended!</div></div>`;
}

setInterval(updateCountdown, 1000);
});

Conclusion

In this tutorial, we learned how to create a countdown timer using Tailwind CSS and JavaScript. We covered the basic structure of the project, the JavaScript code, and the countdown elements. We also discussed the formatting of the remaining time and the updating of the countdown. By following these steps, you can create a visually appealing and functional countdown timer that can be used in various applications.

Remember to make your countdown timer responsive and user-friendly, and to test it thoroughly to ensure it works as expected.

Hope you enjoyed this tutorial and have a nice day!