OneCompiler

Timer

136


<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Countdown Timer</title> <style> body { font-family: sans-serif; text-align: center; } h1 { font-size: 3rem; margin-top: 1rem; margin-bottom: 1rem; } #countdown { display: flex; justify-content: center; align-items: center; font-size: 2rem; margin-bottom: 1rem; } #countdown span { padding: 0.5rem; } #countdown span:not(:last-child) { border-right: 1px solid black; } @media only screen and (max-width: 600px) { h1 { font-size: 2rem; } #countdown { font-size: 1.5rem; } } </style> </head> <body> <h1>Countdown Timer</h1> <form> <label for="date">Date:</label> <input type="date" id="date" name="date" required> <br> <label for="time">Time:</label> <input type="time" id="time" name="time" required> <br> <input type="submit" value="Start Countdown"> </form> <div id="countdown"></div> <script> // Get the form and countdown elements const form = document.querySelector("form"); const countdown = document.getElementById("countdown");
  // Listen for form submission
  form.addEventListener("submit", event => {
    event.preventDefault();
    
    // Get the user's selected date and time
    const date = form.date.value;
    const time = form.time.value;
    const targetDate = new Date(`${date}T${time}`).getTime();
    
    // Update the countdown every second
    const interval = setInterval(() => {
      // Get today's date and time
      const now = new Date().getTime();
      
      // Calculate the distance between now and the target date
      const distance = targetDate - now;
      
      // Time calculations for days, hours, minutes and seconds
      const days = Math.floor(distance / (1000 * 60 * 60 * 24));
      const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      const seconds = Math.floor((distance % (1000 * 60)) / 1000);
      
      // Output the result in an element with id="countdown"
      countdown.innerHTML = `
        <span>${days}d</span>
        <span>${hours}h</span>
        <span>${minutes}m</span>
        <span>${seconds}s</span>
      `;
      
      // If the countdown is finished, write some text
      if (distance < 0) {
        clearInterval(interval);
        countdown.innerHTML = "EXPIRED";
      }
    }, 1000);
  });
</script>
</body> </html> ``