l-emi l-emi - 3 months ago 7
CSS Question

Change color of div according to countdown

I didn't know how to word this properly, but I have a countdown, and I want the color to go from green to red, gradually (like a gradient if that makes sense) as the timer counts down. So when it's 25 minutes it's green, and it completes its change to red as it hits 00:00:00.

I know you can change it based on time but I couldn't find a solution for a gradual change.

I tried the following JS and then calling

changeColor()
upon clicking "go" but it's a bit of a mess, stops the countdown from working and I don't know where to go from here:

function changeColor() {
if (document.getElementById("time").innerHTML === "00:00:00") {
$("#tomato").css("background-color", "#37bd5b");
} else if (document.getElementById("time").innerHTML !== "00:00:00") {
$("#tomato").css("background-color", "#D71F27");
}


Here's the fiddle, I want the red bg to start changing upon clicking go.

EDIT: I eventually want to add in the ability to change the minutes on the countdown.

Answer

You can use the jquery animate function. First include jquery ui so that the color feature works. Then get the time when you click go.

var pieces = startTime.split(":");
var time = new Date();
time.setHours(pieces[0]);
time.setMinutes(pieces[1]);
time.setSeconds(pieces[2]);
var timerSec=time.getSeconds()+time.getMinutes()*60+time.getHours()*3600;
$('#tomato').animate({
  backgroundColor: "#00e50b"
}, timerSec*1000);

In the reset click you also need to add

$('#tomato').stop();
$('#tomato').attr('style', 'background-color:#D72028');

fiddle-I changed the time in the fiddle to be shorter and easier to see the results.

Comments