Search code examples
javascriptcolorsfonts

Changing font colour with Javascript


Apologies for this one but I'm way out of my depth!

I've put together the following Javascript which does a great job of displaying a ticking timer (from 10:00 to 0:00) in a HTML class of timer.

var time = document.getElementsByClassName("timer")
var timings = 600;
var i = 0;
var myInterval = setInterval(Timeout, 1000);

function Timeout() {
  if ((timings - i) % 60 >= 10) {
    time[0].innerHTML = parseInt(`${(timings-i)/60}`) + ":" + `${(timings-i)%60}`;
  } else {
    time[0].innerHTML = parseInt(`${(timings-i)/60}`) + ":0" + `${(timings-i)%60}`;
  }
  i++;
  if ((timings - i) % 60 < 0) {
    clearInterval(myInterval);
  }
}
<div class="timer"></div>

What I want the code to do is change the font colour to red when the timer reaches 0:59. I've tried various solutions but I don't know what the correct code would be or where to put it as every option I've tried has simply broken the script.

Would anyone out there be able to shed some light and save the small handful of hair I have left?!

Many thanks in advance.


Solution

  • For the good of the hair, I added a condition (timings - i) === 59 inside the Timeout function. This condition checks if the remaining time is equal to 59 seconds, which corresponds to 0:59 on the timer. When this condition is true, it sets the font color of the timer element to red using time[0].style.color = "red";.

    var time = document.getElementsByClassName("timer");
    var timings = 100;
    var i = 0;
    var myInterval = setInterval(Timeout, 1000);
    
    function Timeout() {
      if ((timings - i) % 60 >= 10) {
        time[0].innerHTML = parseInt(`${(timings - i) / 60}`) + ":" + `${(timings - i) % 60}`;
      } else {
        time[0].innerHTML = parseInt(`${(timings - i) / 60}`) + ":0" + `${(timings - i) % 60}`;
      }
    
      if ((timings - i) === 59) {
        time[0].style.color = "red";
      }
    
      i++;
      if ((timings - i) % 60 < 0) {
        clearInterval(myInterval);
      }
    }
     
          <div class="timer"></div>