+ 2

switch case problem - need help

Hey im just starting to learn javascript and i dont get why my code wont work. The color of my page should change depending on what time it is. As a normal if-else code it worked fine. I tried changing it to switch-case and probably messed it all up. Dont know if the braces after the cases are correct, but I tried it without them and it didn't work either.. Can anyone help? Many thanks in advance! https://code.sololearn.com/WyflQ0x5JV8f var date = new Date(); var hours = 12; //date.getHours(); var daytime; console.log(hours); switch (hours) { case (hours <= 4): console.log("Good Night!"); body.style.backgroundColor = "#a4cdf5"; break; case (hours < 12) : console.log("Good Morning!"); body.style.backgroundColor = "#f5f5a4"; break; case (hours < 17) : console.log("Good Afternoon!"); body.style.backgroundColor = "#f5cda4"; break; case (hours < 22): console.log("Good Evening!"); body.style.backgroundColor = "#a4f5cd"; break; default: console.log("Good Night!"); body.styl

22nd Apr 2019, 4:19 PM
Sarah Hilz
Sarah Hilz - avatar
4 Antworten
+ 3
`switch` only checks for finite values, it doesn't work with ranges like `if` statement. Seeing you work with hour ranges; I think you better stick to using `if` statement. Another thing; you might wanna wrap the code within a function, and set the function as the load event handler for the window. window.onload = function() { // your code here } Hth, cmiiw
22nd Apr 2019, 5:04 PM
Ipang
+ 2
Okay good to know! Guess I'll have to stick to if-statements then.. And thanks for the function-suggestion, will do so!
23rd Apr 2019, 10:13 PM
Sarah Hilz
Sarah Hilz - avatar
+ 1
after (hours) make use of curly braces instead of parenthesis, ensure to close them
4th May 2019, 10:09 AM
Benjamin Michaels
Benjamin Michaels - avatar
0
Hlo
2nd Jul 2019, 6:42 PM
Jaybhaye Anil Laxman
Jaybhaye Anil Laxman - avatar