Reputation: 23
I'm coding a site with my friend, we are very new to coding. We would like our site to change color gradually every second according to the time of day. We have no clue where to even start, other than using a javascript function. Please help!!!! We have coded a clock into our site
function time(){
var today = new Date();
var h = today.getHours()
if (h>12) {h= h- "12"} ;
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('clocky').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(time, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i};
return i;
}
This is as far as we have gotten other than general html for the clock and css. How would you code the changing background according to time?
Upvotes: 1
Views: 8015
Reputation: 11
I know the question asks for a javscript solution, but the animation you are seeking is possible with a css-only solution and should be more performant.
I've written a more complete solution using a tiny bit of php to fetch daylight information for given lat/long coordinates and change the color of the page in real-time according to the time of day.
for a demo see here:
http://shawnfromportland.com/circadianCssWithPhp/
for the source check it out here:
https://github.com/shawnfromportland/circadianCssWithPhp
Upvotes: 0
Reputation: 57832
Well, now you'll need to make some decisions.
CSS lets you specify colors in the RGB format using numeric values from 0-255 (e.g. background-color: rgb(0,0,0)
for a black background, and background-color: rgb(255,255,255)
for a white background.
Assuming you want to use that method for specifying the color, you'll need to decide how you want the current time to map to those values. Once you have that figured out, all you'll need to do is set the background color style on the <html>
element.
Upvotes: 1
Reputation: 1279
https://jsfiddle.net/f9b9sbr4/1/
function time(){
var today = new Date();
var h = today.getHours()
if (h>12) {h= h- "12"} ;
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('clocky').innerHTML = h + ":" + m + ":" + s;
var r = parseInt(s) * 1;
var g = parseInt(s) * 3;
var b = parseInt(s) * 5;
document.body.style.backgroundColor = 'rgb(' + r + ',' + g + ',' + b + ')';
var t = setTimeout(time, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i};
return i;
}
time();
Upvotes: 3