To create a JavaScript countdown timer, follow these steps:
- HTML Structure: Create a container for the countdown display.
1 2 3 4 5 6 7 |
<div class=“countdown-container”> <div id=“days”>00</div> <div id=“hours”>00</div> <div id=“minutes”>00</div> <div id=“seconds”>00</div> </div> |
- CSS Styling: Style the container and countdown elements.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
.countdown–container { display: flex; justify–content: center; align–items: center; gap: 2rem; font–family: Arial, sans–serif; color: #333; } #days, #hours, #minutes, #seconds { width: 50px; height: 50px; background–color: white; border–radius: 50%; display: flex; justify–content: center; align–items: center; box–shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } |
- JavaScript Logic: Implement the countdown functionality.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
function updateCountdown() { const targetDate = new Date(‘2024-01-01T00:00:00’).getTime(); const now = new Date().getTime(); const difference = targetDate – now; if (difference <= 0) { clearInterval(interval); alert(‘Time is up!’); return; } const days = Math.floor(difference / (1000 * 60 * 60 * 24)); const hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60)); const seconds = Math.floor((difference % (1000 * 60)) / 1000); document.getElementById(‘days’).innerHTML = days.toString().padStart(2, ‘0’); document.getElementById(‘hours’).innerHTML = hours.toString().padStart(2, ‘0’); document.getElementById(‘minutes’).innerHTML = minutes.toString().padStart(2, ‘0’); document.getElementById(‘seconds’).innerHTML = seconds.toString().padStart(2, ‘0’); } // Start the countdown const interval = setInterval(updateCountdown, 1000); updateCountdown(); // Initial call to set starting values |
This code creates a visually appealing countdown timer that updates every second. The timer displays days, hours, minutes, and seconds until a specified target date. When the countdown reaches zero, it stops and shows an alert message.
Features:
– Clean and responsive design using Flexbox.
– Each time unit is displayed in a circular container with a modern shadow effect.
– Automatic padding for single-digit numbers to maintain consistent formatting.
– Graceful handling of the end condition with an alert notification.
Leave a Reply
You must be logged in to post a comment.