I need to create a link on an HTML page that can only be clicked at a specific time. I have the following code but it doesn’t seem to be working. Preferably the link should be active at a specific time and date. For example, the link could be active at 10:00AM on 10/24/2024 and then inactive either at a specific time or number of hours later.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<style>
#myButton {
padding: 10px 20px;
background-color: gray;
color: white;
border: none;
text-decoration: none;
display: inline-block;
pointer-events: none;
cursor: not-allowed;
}
#myButton.active {
background-color: blue;
cursor: pointer;
pointer-events: auto;
}
#myButton.disabled {
background-color: red;
cursor: not-allowed;
pointer-events: none;
}
</style>
</head>
<body>
<h1>Click the link between 10:00 AM and 10:15 AM Eastern Time</h1>
<a href="#" class="disabled" id="myButton">Link Disabled</a>
<script>
const easternTimeOffset = -4;
const targetStartDate = new Date();
const targetEndDate = new Date();
targetStartDate.setUTCHours(10 + easternTimeOffset, 0, 0, 0);
targetEndDate.setUTCHours(10 + easternTimeOffset, 15, 0, 0);
const button = document.getElementById("myButton");
function checkTime() {
const now = new Date();
if (now >= targetStartDate && now < targetEndDate) {
button.href = "https://www.britannica.com/science/world-map";
button.classList.add("active");
button.classList.remove("disabled");
button.textContent = "Click Me Now!";
} else if (now >= targetEndDate) {
button.href = "#";
button.classList.remove("active");
button.classList.add("disabled");
button.textContent = "Link Disabled";
}
}
checkTime();
setInterval(checkTime, 1000);
</script>
</body>
</html>
2
Answers
In the example below, function
linkEvent()
renders the HTML to a given element (@param selector
) which displays the given start date and time (@param start
) and the end time which is determined by the given number of seconds (@param duration
). The HTML includes the<a>
nchor (akalink
) as well. The functionupdateTime()
is then called every second to determine when thelink
is de/activated.The function
demo()
is included to show it working with a start time of 10 seconds after current time and an end time of 60 seconds. Details are commented in the example.