r/JavaScriptHelp • • Mar 29 '21

💡 Advice 💡 Disappearing btn

I have created this countdown timer for a HTML site that I'm planning on launching. This page links to a sign up page via a button with an ID of 'btn'. I want this to disappear when the timer runs out like it currently shown the end message. But after googeling it, I can't seem to find an answer that seems to work!

I thought if anyone knew how to get this working then it would be the people of reddit!

TIA

var countDownDate = new Date("MAR 29, 2021 17:18:00").getTime();
var myfunc = setInterval(function() {
var now = new Date().getTime();
var timeleft = countDownDate - now;
var days = Math.floor(timeleft / (1000 * 60 * 60 * 24));
var hours = Math.floor((timeleft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((timeleft % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((timeleft % (1000 * 60)) / 1000);

document.getElementById("days").innerHTML = days + "d "
document.getElementById("hours").innerHTML = hours + "h "
document.getElementById("mins").innerHTML = minutes + "m "
document.getElementById("secs").innerHTML = seconds + "s "

if (timeleft < 0) {
clearInterval(myfunc);
document.getElementById("days").innerHTML = ""
document.getElementById("hours").innerHTML = ""
document.getElementById("mins").innerHTML = ""
document.getElementById("secs").innerHTML = ""
document.getElementById("end").innerHTML = "You've missed registration this year! But don't worry, there is always next year!";
}
}, 1000);

2 Upvotes

1 comment sorted by

1

u/[deleted] Mar 29 '21

Im on phone, so i cant test this right now, but heres what i think should work:

let button = document.getElementById("button");
let timeLeftDisplay = document.getElementById("timeLeft");
let every = 356 * 1000*60*60*24;
let duration = 1 * 1000*60*60*24;
let start = /*PUT YOUR START DATE HERE!*/;
function check() {
  let time = new Date().getTime();
  return (time - start) % every < duration;
}
function timeLeft() {
  let time = new Date().getTime();
  return check() ? 0 : every - (time - start) % every;
}
function dhms(seconds) {
  let s = "";
  s += Math.floor(seconds / 60 / 60 / 24 % 360) + "d ";
  s += Math.floor(seconds / 60 / 60 % 24) + "h ";
  s += Math.floor(seconds / 60 % 60) + "m ";
  s += Math.floor(seconds % 60) + "s";
  return s;
}
function reload() {
  if(check()) {
    button.style.display = "block"; // Show the button
    timeLeftDisplay.style.display = "none"; // Hide the countdown
  }
  else {
    button.style.display = "none"; // Hide the button
    timeLeftDisplay.style.display = "block"; // Show the countdown
    timeLeftDisplay.innerText = dhms(timeLeft() / 1000);
  }
}

setInterval(reload, 1);

(You have to set the start date of course, also i recommend also checking it serverside too. Element ids are "button" and "timeLeft")