DEV Community

Cover image for How to create a countdown with Tailwind CSS and Alpinejs
Michael Andreuzza
Michael Andreuzza

Posted on

How to create a countdown with Tailwind CSS and Alpinejs

Let's build a fun countdown timer with Tailwind CSS and Alpinejs.

See it live and get the code

What are 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.

Let's get started

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

  • x-data="{ endDate: new Date('2024-12-31T23:59:59').getTime(), remainingTime: 0, formatTime(time) {: This is the data that will be used to store the end date and remaining 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);: This is the calculation that will be used to format the remaining time.
  • setInterval(() => {: This is the event listener that will update the remaining time when the end date changes.
  • const now = new Date().getTime();: This is the variable that will be used to calculate the remaining time.
  • const remainingTime = endDate - now;: This is the calculation that will be used to update the remaining time.
  • `$data.remainingTime = remainingTime > 0 ?
  • : 0;: This is the condition that will be checked when the remaining time is updated.
  • }, 1000);: This is the interval that will be used to update the remaining time.
  • x-if="remainingTime > 0": This is the condition that will be checked when the remaining time is greater than 0.
  • x-text="formatTime(remainingTime).days": This is the display of the days remaining.
  • x-text="formatTime(remainingTime).hours": This is the display of the hours remaining.
  • x-text="formatTime(remainingTime).minutes": This is the display of the minutes remaining.
  • x-text="formatTime(remainingTime).seconds": This is the display of the seconds remaining.
  • <div>Countdown has ended!</div>: This is the display of the countdown has ended message.

html
<div
x-data="{
endDate: new Date('2024-12-31T23:59:59').getTime(),
remainingTime: 0,
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 };
}
}"
x-init="() => {
setInterval(() => {
const now = new Date().getTime();
const remainingTime = endDate - now;
$data.remainingTime = remainingTime > 0 ? remainingTime : 0;
}, 1000);
}">
<template x-if="remainingTime > 0">
<div>
<div>
<div
x-text="formatTime(remainingTime).days">
</div>
<div>Days</div>
</div>
<div>
<div
x-text="formatTime(remainingTime).hours">
</div>
<div>Hours</div>
</div>
<div>
<div
x-text="formatTime(remainingTime).minutes">
</div>
<div>Minutes</div>
</div>
<div>
<div
x-text="formatTime(remainingTime).seconds">
</div>
<div>Seconds</div>
</div>
</div>
</template>
<template x-if="remainingTime <= 0">
<div>
<div>Countdown has ended!</div>
</div>
</template>
</div>

Concluision

This is a simple countdown timer that can be used for any type of content, such as movies, books, products, or services. The code is easy to understand and the structure is clear. The use of Tailwind CSS and Alpine.js makes it easy to style the countdown timer and add interactivity. Remeber to make it as accessible as possible, and you're good to go!

Hope you enjoyed this tutorial and have a great day!

Top comments (0)