0

I'm new to coding, and I'm looking to optimize this JavaScript code ? What is your recommendation? Should i use a variable pour the hour number? How could i try to not repeat the same else if and make it shorter?

var currentTime = new Date().getHours();
            if (0 == currentTime) {
                document.body.className = "sky-gradient-00";
            }
            else if (1 == currentTime) {
                document.body.className = "sky-gradient-01";
            }
            ...
            else if (22 == currentTime) {
                document.body.className = "sky-gradient-22";
            }
            else if (23 == currentTime) {
                document.body.className = "sky-gradient-23";
            }
html,
body {
  height: 100%;
  width: 100%;
}

.sky-gradient-00,
.sky-gradient-24 {
  background: #00000c;
}

.sky-gradient-01 {
  background: linear-gradient(to bottom, #020111 85%, #191621 100%);
}

.sky-gradient-22 {
  background: linear-gradient(to bottom, #090401 50%, #4B1D06 100%);
}

.sky-gradient-23 {
  background: linear-gradient(to bottom, #00000c 80%, #150800 100%);
}
<html>
  <body class="">
  </body>
</html>

0

2 Answers 2

3

Like you said use a variable. Just use the hours and pad it when it is less than 10.

if(currentTime < 10) currentTime = "0" + currentTime;
document.body.className = "sky-gradient-" + currentTime;
Sign up to request clarification or add additional context in comments.

2 Comments

Can you tell me why i should use "if (currentTime < 10)" ?
@Wally - That part is to always have the value with two digits... (add the zero to the left)
0
var currentTime = new Date().getHours();
var cls = "sky-gradient-";

if (currentTime < 10) {
   cls = cls + "0" + currentTime;
} else {
   cls += currentTime ;
}
document.body.className = cls;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.