mardi 14 juillet 2020

Using if/else statement with time to change an objects class

I want to be able to determine the class of an object depending on the time - I currently have two classes, recommendedspot and notrecommended. I have tried the code below however the image does not appear as I would like.

Below is my code:

var time = new Date().getHours();
if (time > 9 && time < 17) {
  document.getElementById("spotsouth").classList.remove('notrecommended');
  document.getElementById("spotsouth").classList.add('recommendedspot');
} else if (time > 6 && time < 9) {
  document.getElementById("spotnorth").classList.remove('notrecommended');
  document.getElementById("spotnorth").classList.add('recommendedspot');
} else if (time > 17 && time < 21) {
  document.getElementById("spotnorth").classList.remove('notrecommended');
  document.getElementById("spotnorth").classList.add('recommendedspot');
} else {}
.notrecommended {
  display: none;
}

.recommendedspot {
  display: inline;
  margin-left: 15px;
  max-width: 50px;
}
<img id="spotsouth" src="site-logo.png" alt="spot south" class="notrecommended">
<img id="spotnorth" src="site-logo.png" alt="spot north" class="notrecommended">

If anyone knows where I have gone wrong, please let me know as I can't seem to figure it out! Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire