Last active
April 4, 2023 23:23
-
-
Save ihorduchenko/6f518691b939a78276b2d8ad8631fccb to your computer and use it in GitHub Desktop.
Vanilla JS countdown timer to specific date
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="countTimer" data-date="01 Jan 2030 00:00:00 GMT"> | |
<div class="countdown-wrapper"> | |
<div class="countdown-cell"> | |
<span class="timer-number tDays">00</span> | |
<div class="timer-caption">Days</div> | |
</div> | |
<div class="countdown-cell">·</div> | |
<div class="countdown-cell"> | |
<span class="timer-number tHours">00</span> | |
<div class="timer-caption">hours</div> | |
</div> | |
<div class="countdown-cell">·</div> | |
<div class="countdown-cell"> | |
<span class="timer-number tMinutes">00</span> | |
<div class="timer-caption">Minutes</div> | |
</div> | |
<div class="countdown-cell">·</div> | |
<div class="countdown-cell"> | |
<span class="timer-number tSeconds">00</span> | |
<div class="timer-caption">Seconds</div> | |
</div> | |
</div> | |
</div> | |
<script> | |
function addZeroToOutput(num) { | |
let output = num < 10 ? '0' + num : num; | |
return output; | |
} | |
let countdownTimers = document.querySelectorAll('.countTimer'); | |
countdownTimers.forEach(function(timer) { | |
let daysEl = timer.querySelector('.tDays'); | |
let hoursEl = timer.querySelector('.tHours'); | |
let minutesEl = timer.querySelector('.tMinutes'); | |
let secondsEl = timer.querySelector('.tSeconds'); | |
let deadlineDate = new Date(timer.dataset.date); | |
let second = 1000, | |
minute = second * 60, | |
hour = minute * 60, | |
day = hour * 24; | |
let countDown = new Date(deadlineDate).getTime(), | |
x = setInterval(function() { | |
let now = new Date().getTime(), | |
distance = countDown - now; | |
daysEl.innerText = addZeroToOutput(Math.floor(distance / (day))), | |
hoursEl.innerText = addZeroToOutput(Math.floor((distance % (day)) / (hour))), | |
minutesEl.innerText = addZeroToOutput(Math.floor((distance % (hour)) / (minute))), | |
secondsEl.innerText = addZeroToOutput(Math.floor((distance % (minute)) / second)); | |
if (distance < 0) { | |
countdownTimers.parentNode.removeChild(countdownTimers); | |
clearInterval(x); | |
} | |
}, 1000); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment