JSFiddle - React, Tailwind, and code Playground
HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<p style="font-size: 36px; font-weight: lighter; text-align: center;">Compte à rebours</p>
<div class="center-div" id="countdown">
<strong>Temps restant</strong> :<br />
<span id="countdown_year">--</span>
<span id="countdown_month">--</span>
<span id="countdown_day">--</span>
<span id="countdown_hour">--</span>
<span id="countdown_min">--</span>
<span id="countdown_sec">--</span>
</div>
<!-- <script src="./countdown.js"></script> -->
</body>
</html>
CSS
.center-div {
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 500px;
height: 20px;
background-color: #FFFFFF;
border-radius: 3px;
font-size: 24px;
text-align: center;
}
/* Cette class s'occupera de masquer les compteurs affichants 0 */
.hidden {
display: none;
}
JavaScript
const countdownManager = {
// Date cible du compte à rebours (00:00:00) - targetTime: new Date('2022-11-05 10:20:30'), May 10 00:00:00 2022
targetTime: new Date("Jul 22 15:00:00 2022"),
// Initialisation du compte à rebours (à appeler 1 fois au chargement de la page)
init(options = {}) {
this.displayElement = {
year: document.getElementById("countdown_year"),
month: document.getElementById("countdown_month"),
day: document.getElementById("countdown_day"),
hour: document.getElementById("countdown_hour"),
min: document.getElementById("countdown_min"),
sec: document.getElementById("countdown_sec"),
}
this.options = {
onFinish: () => {},
...options
}
if (options.targetTime) {
const time = options.targetTime
this.targetTime = time instanceof Date ? time : new Date(time)
}
if (options.birthdayMode) {
this.setTargetTimeBirthdayYear()
}
this.tick()
this.interval = window.setInterval(countdownManager.tick.bind(this), 1000)
},
// Met à jour le compte à rebours (tic d'horloge)
tick() {
let timeNow = Date.now()
// On s'assure que le temps restant ne soit jamais négatif (ce qui est le cas dans le futur de targetTime)
if (timeNow > this.targetTime) {
timeNow = this.targetTime
}
// Calcul du temps restant
const diff = this.dateDiff(timeNow, this.targetTime)
const areYearsHidden = diff.year <= 0
const areMonthsHidden = areYearsHidden && diff.month <= 0
const areDaysHidden = areMonthsHidden && diff.day <= 0
const areHoursHidden = areDaysHidden && diff.hour <= 0
const areMinutesHidden = areHoursHidden && diff.min <= 0
this.displayElement.year.textContent = `${diff.year} années`
this.displayElement.year.classList.toggle("hidden", areYearsHidden)
this.displayElement.month.textContent = `${diff.month} mois`
this.displayElement.month.classList.toggle("hidden", areMonthsHidden)
...