Brett Carwile Brett Carwile - 1 year ago 68
CSS Question

Color Change at Certain Time of Day not Working in Js

So, basically, I've created some Javascript that after a certain time of day (certain hours) it will change the background color of the page. I got confused on how to go about doing it, but after asking on this site, I was able to be pointed in the right direction.

Here is the code (Information about my problem is below the code):

//determines the bg color
var curHour = new Date().getHours(); //finds the current hour
var background = document.getElementById('myBody'); //gets background
if (curHour > 4 && curHour < 11){ = "lightblue"; //Morning
else if (curHour > 11 && curHour < 17) { = "#3a9fe5"; //around afternoon
else if (curHour > 17 && curHour < 21) { = "#102a55"; //evening
else { = "black"; //night
//Please note: this isn't ALL of the javascript, just the bit I'm using to change the color

#myBody {
background-color: lightSeaGreen; /*This is the default color in case something goes wrong with the JS*/
z-index: -999;

<!DOCTYPE html>
<script src="JsSnow.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<body id="myBody">
<canvas id="myCanvas"></canvas>

Okay my problem is when I view the page (It is currently around 11:30 am, where I am), the background color is showing up as black, eventhough black shouldn't show up until past 9pm (i.e. 21st hour)

What i tried to do to fix the code was change the else statement for the black color to:

else if (curHour > 21 && curHour < 4) { = "black"; //night

Unfortunately, when I tried that, it caused everything else on the page to disappear , and made the page become its default color of lightSeaGreen.

Oddly though, the page displayed the correct color before 11am, and yesterday it displayed the correct color for evening and night. . .

Answer Source

You're lacking cases for curHour==11, your code is only checking for strictly smaller and strictly larger, so for the whole hour of 11am and 5pm, you'll fall through to black.

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