Modern Countdown Timer In Vanilla JavaScript – Ls Countdown

Category: Date & Time , Javascript | May 10, 2019
Author: leandrosimoes
Views Total: 1,486
Official Page: Go to website
Last Update: May 10, 2019
License: MIT

Preview:

Modern Countdown Timer In Vanilla JavaScript – Ls Countdown

Description:

The Ls Countdown library lets you create a modern, configurable countdown timer for coming soon, under construction, maintenance mode pages.

How to use it:

Create a countdown timer with days, hours, minutes, seconds slots.

<div id="countdown">
  <div class="countdown-item days">0</div>
  <div class="countdown-item hours">0</div>
  <div class="countdown-item minutes">0</div>
  <div class="countdown-item seconds">0</div>
</div>

The example CSS for the countdown timer.

#countdown {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
}

.countdown-item {
  font-size: 20px;
  border-radius: 50%;
  text-align: center;
  width:100px;
  height: 100px;
  line-height: 100px;
  position: relative;
  opacity: 0;
  margin: 5px;
}

.countdown-item.show {
  animation: fadein 2s forwards;
}

.countdown-item::before {
  position: absolute;
  content: ' ';
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-color: #fff;
  left: 0;
  top: 0;
  opacity: .1;
}

.countdown-item.days {
  animation-delay: 1s;
}

.countdown-item.hours {
  animation-delay: 1.5s;
}

.countdown-item.minutes {
  animation-delay: 2s;
}

.countdown-item.seconds {
  animation-delay: 2.5s;
}

.countdown-item.days::after {
  content: attr(data-days);
}

.countdown-item.hours::after {
  content: attr(data-hours);
}

.countdown-item.minutes::after {
  content: attr(data-minutes);
}

.countdown-item.seconds::after {
  content: attr(data-seconds);
}

@keyframes fadein {
  from { opacity: 0; }
  to { opacity: 1; }
}

Download and import the ‘ls-countdown.min.js’ into the document.

<script src="/js/ls-countdown.min.js"></script>

The example JavaScript to activate the countdown timer.

document.addEventListener("DOMContentLoaded", function () {
  let currentYear = new Date().getFullYear();
  let targetDate = new Date(currentYear + 1, 0, 1);
  let onStart = () => {
      document.querySelectorAll('.countdown-item').forEach(item => item.classList.add('show'))
  }
  let onTick = ({ days, hours, minutes, seconds }) => {
      document.querySelector('.countdown-item.days').innerHTML = days;
      document.querySelector('.countdown-item.hours').innerHTML = hours;
      document.querySelector('.countdown-item.minutes').innerHTML = minutes;
      document.querySelector('.countdown-item.seconds').innerHTML = seconds;
  };
  let options = new LsCountdownOptions({ targetDate, onStart, onTick });
  let countdown = new LsCountdown(options);

  countdown.start();
  window.mycountdown = countdown;
});

Stop the countdown timer manually.

countdown.stop();

Changelog:

v1.1.0 (05/10/2019)

  • Now the years amount is returned too

You Might Be Interested In:


Leave a Reply