diff --git a/29 - Countdown Timer/changi.js b/29 - Countdown Timer/changi.js new file mode 100644 index 0000000..adfecb8 --- /dev/null +++ b/29 - Countdown Timer/changi.js @@ -0,0 +1,60 @@ +let countdown; // interval +const timerDisplay = document.querySelector(".display__time-left"); +const endTime = document.querySelector(".display__end-time"); +const buttons = document.querySelectorAll("[data-time]"); + +function timer(seconds) { + clearInterval(countdown); + + const now = Date.now(); + const then = now + seconds * 1000; + displayTimeLeft(seconds); + displayEndTime(then); + + countdown = setInterval(() => { + const secondsLeft = Math.round((then - Date.now()) / 1000); + + if (secondsLeft < 0) { + clearInterval(countdown); + return; + } + + displayTimeLeft(secondsLeft); + }, 1000); +} + +function displayTimeLeft(seconds) { + const minutes = Math.floor(seconds / 60); + const remainderSeconds = seconds % 60; + const display = `${minutes}:${ + remainderSeconds < 10 ? "0" : "" + }${remainderSeconds}`; + document.title = display; + timerDisplay.textContent = display; +} + +function displayEndTime(timestamp) { + const end = new Date(timestamp); + const hour = end.getHours(); + const adjustedHour = hour > 12 ? hour - 12 : hour; + const minutes = end.getMinutes(); + endTime.textContent = `Be Back At ${adjustedHour}:${ + minutes < 10 ? "0" : "" + }${minutes}`; +} + +function startTimer() { + const seconds = parseInt(this.dataset.time); + timer(seconds); +} + +buttons.forEach((button) => button.addEventListener("click", startTimer)); + +// get time from form tag +document.customForm.addEventListener("submit", function (e) { + e.preventDefault(); + const mins = this.minutes.value; + console.log(mins); + timer(mins * 60); + this.reset(); +}); diff --git a/29 - Countdown Timer/index.html b/29 - Countdown Timer/index.html index d54f447..ab4465a 100644 --- a/29 - Countdown Timer/index.html +++ b/29 - Countdown Timer/index.html @@ -1,29 +1,34 @@ - - - Countdown Timer - - - - -
-
- - - - - -
- -
+ + + Countdown Timer + + + + +
+
+ + + + + +
+ +
+
+
+

+

+
-
-

-

-
-
- - + + +