main.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import '../styles/counter.css'
  2. import { Countdown } from './counter.js'
  3. const buttonInit = document.querySelector('#init');
  4. const buttonStart = document.querySelector('#start');
  5. // Get the new year
  6. const getNewYear = () => {
  7. const currentYear = new Date().getFullYear();
  8. return new Date(`January 01 ${currentYear + 1} 00:00:00`);
  9. };
  10. // select elements
  11. const app = document.querySelector('.countdown-timer');
  12. const message = document.querySelector('.message');
  13. const heading = document.querySelector('h1');
  14. const format = (t) => {
  15. return t < 10 ? '0' + t : t;
  16. };
  17. const render = (time) => {
  18. app.innerHTML = `
  19. <div class="count-down">
  20. <div class="timer">
  21. <h2 class="days">${format(time.days)}</h2>
  22. <small>Days</small>
  23. </div>
  24. <div class="timer">
  25. <h2 class="hours">${format(time.hours)}</h2>
  26. <small>Hours</small>
  27. </div>
  28. <div class="timer">
  29. <h2 class="minutes">${format(time.minutes)}</h2>
  30. <small>Minutes</small>
  31. </div>
  32. <div class="timer">
  33. <h2 class="seconds">${format(time.seconds)}</h2>
  34. <small>Seconds</small>
  35. </div>
  36. </div>
  37. `;
  38. };
  39. const showMessage = () => {
  40. message.innerHTML = `Terminé !`;
  41. app.innerHTML = '';
  42. heading.style.display = 'none';
  43. };
  44. const hideMessage = () => {
  45. message.innerHTML = '';
  46. heading.style.display = 'block';
  47. };
  48. const complete = () => {
  49. showMessage();
  50. // restart the countdown after showing the
  51. // greeting message for a day ()
  52. setTimeout(() => {
  53. hideMessage();
  54. countdownTimer.setExpiredDate(getNewYear());
  55. }, 1000 * 60 * 60 * 24);
  56. };
  57. const countdownTimer = new Countdown(
  58. getNewYear(),
  59. render,
  60. complete
  61. );