l-emi l-emi - 1 year ago 78
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

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 Source

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();
var timerSec=time.getSeconds()+time.getMinutes()*60+time.getHours()*3600;
  backgroundColor: "#00e50b"
}, timerSec*1000);

In the reset click you also need to add

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download