I'm trying to build a memento mori kind of clock, and I want to make it so people can insert a certain date in there.
But when I get the element by ID in JS I get null.
Tried to get make it a string and test it with alerts, but I got no results. It was still null.
I mean, the alert box is empty, so I assume it is null.
Some of my assumptions are:
- There's a problem with the id or with the document.getElementById("targetDate").innerHTM part
- I tried to get it as a string and then convert it to date as I did initially using this: new Date("Jan 5, 2090 15:37:25").getTime()
- I don't use the date functions the right way
- Maybe the approach should be changed to getting the day, month, year & hours separately
Here's the code:
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>💀 Days Until Death</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="main-div">
<h2>💀 Days Until Death</h2>
<hr>
<h1><p id="demo"></p></h1>
<hr>
<input id="targetDate" type="input" name="date" value="Jan 1, 2090 15:37:25">
<input onclick="ChangeDate()" type="submit" name="" value="Change Date">
</div>
</body>
<script type="text/javascript" src="script.js"></script>
</html>
JavaScript:
// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2090 15:37:25").getTime();
function ChangeDate() {
var targetDate = String(document.getElementById("targetDate").innerHTML);
alert(targetDate);
countDownDate = new Date(targetDate).getTime();
}
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
