Home > Blockchain >  Change Text based on time with Javascript
Change Text based on time with Javascript

Time:05-12

Right now I'm pulling in the current time in the span #time, and would like to add custom messages into #officehours based on the time, but am having trouble getting them to play nicely with each other.

//Timestamp
function getTimeCurrentTime() {
   let time = new Date();
   return time.toLocaleString('en-US').split(',')[1];
}

function updateCurrentTime() {
   let timeNode = document.getElementById('time');
   timeNode.innerHTML = getTimeCurrentTime();
}

setInterval(updateCurrentTime, 1000);

function officeHours() {
  var myDate = new Date();
  var hrs = myDate.getHours();

  var greet;

  if (hrs < 12)
      greet = 'Good Morning';
  else if (hrs >= 12 && hrs <= 17)
      greet = 'Good Afternoon';
  else if (hrs >= 17 && hrs <= 24)
      greet = 'Good Evening';

      document.getElementById('officehours').innerHTML = greet;
}
<div >
      <span>Office Hours:</span><br>
      <span>M-F, 9:00-5:00</span><br>
      <span>Currently:</span><span id="time"></span><br>
      <span>We Are:</span><span id="officehours"></span>
   </div>

CodePudding user response:

Call the function.

You've defined a function called updateCurrentTime:

function updateCurrentTime() {
  //...
}

And you call it at 1-second intervals:

setInterval(updateCurrentTime, 1000);

You've also defined a function called officeHours:

function officeHours() {
  //...
}

But you never call it. In order to execute a function, you have to invoke it. Presumably in this case the intent is to invoke it from the updateCurrentTime function. For example:

function updateCurrentTime() {
  let timeNode = document.getElementById('time');
  timeNode.innerHTML = getTimeCurrentTime();
  officeHours();
}
  • Related