@orpha
To create a countdown using Moment.js, you can follow these steps:
Here's an example code snippet to help you understand the process:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<!DOCTYPE html> <html> <head> <title>Countdown using Moment.js</title> <script src="https://momentjs.com/downloads/moment.min.js"></script> </head> <body> <h1>Countdown</h1> <p>Remaining time: <span id="countdown"></span></p> <script> // Get the current date and time var now = moment(); // Set the target date and time var targetDate = moment("2022-01-01 00:00:00"); // Calculate the remaining time var remainingTime = moment.duration(targetDate.diff(now)); function updateCountdown() { // Check if the target date has passed if (remainingTime <= 0) { document.getElementById("countdown").innerHTML = "Countdown complete!"; } else { // Update the countdown display var days = remainingTime.days(); var hours = remainingTime.hours(); var minutes = remainingTime.minutes(); var seconds = remainingTime.seconds(); document.getElementById("countdown").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s"; // Subtract 1 second from the remaining time remainingTime.subtract(1, "s"); } } // Call the updateCountdown function every second setInterval(updateCountdown, 1000); </script> </body> </html> |
In this example, the countdown is set to the target date of "2022-01-01 00:00:00". The countdown will continuously update the display in the specified HTML element until the target date is reached.