JavaScript Countdown

by Kevin Pliester

HTML

<p>
Zieldatum: 01.03.20202, 12:00:00
</p>

<div class="countdown" id="countdown1" data-end="2021-03-01, 12:00:00">
  <span class="timeel days">00</span>
  <span class="timeel timeRefDays">Tage</span>
  <span class="timeel hours">00</span>
  <span class="timeel timeRefHours">Stunden</span>
  <span class="timeel minutes">00</span>
  <span class="timeel timeRefMinutes">Minuten</span>
  <span class="timeel seconds">00</span>
  <span class="timeel timeRefSeconds">Sekunden</span>
</div>

CSS

@import url('https://fonts.googleapis.com/css2?family=Open+Sans&display=swap');

body {
  font-family: 'Open Sans', sans-serif;
}

.countdown {
  margin-bottom: 20px;
}

.countdown .timeel {
  display: inline-block;
  padding: 10px;
  background: #151515;
  margin: 0;
  color: white;
  min-width: 2.6rem;
  border-radius: 10px 0 0 10px;
}

.countdown span[class*="timeRef"] {
  border-radius: 0 10px 10px 0;
  margin-left: 0;
  background: #337e96;
  color: white;
  margin-right: 13px;
}

JavaScript

$(function() {
  $(".countdown").each(function() {

    let id = $(this).attr("id");
    let countdown = $(this).attr("data-end");
    countDownToTime(countdown, id);

  });
});

/*
 * Basic Count Down to Date and Time
 * Author: @guwii / guwii.com
 * https://guwii.com/bytes/easy-countdown-to-date-with-javascript-jquery/
 */
function countDownToTime(countTo, id) {
  countTo = new Date(countTo).getTime();
  var now = new Date(),
    countTo = new Date(countTo),
    timeDifference = (countTo - now);

  var secondsInADay = 60 * 60 * 1000 * 24,
    secondsInAHour = 60 * 60 * 1000;

  days = Math.floor(timeDifference / (secondsInADay) * 1);
  hours = Math.floor((timeDifference % (secondsInADay)) / (secondsInAHour) * 1);
  mins = Math.floor(((timeDifference % (secondsInADay)) % (secondsInAHour)) / (60 * 1000) * 1);
  secs = Math.floor((((timeDifference % (secondsInADay)) % (secondsInAHour)) % (60 * 1000)) / 1000 * 1);

  var idEl = document.getElementById(id);
  idEl.getElementsByClassName('days')[0].innerHTML = days;
  idEl.getElementsByClassName('hours')[0].innerHTML = hours;
  idEl.getElementsByClassName('minutes')[0].innerHTML = mins;
  idEl.getElementsByClassName('seconds')[0].innerHTML = secs;

  clearTimeout(countDownToTime.interval);
  countDownToTime.interval = setTimeout(function() {
    countDownToTime(countTo, id);
  }, 1000);
}