Solution 1 :

How about this:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
 window.onload = function() {
  var hour = new Date().getHours();
  if (hour < 12) {
    window.location.replace("http://xxx.example.com");
   } else {
    window.location.replace("http://yyy.example.com");
   }
  }
 </script>

 </body>
</html>

Solution 2 :

I think this is what you need:

<p id="demo"></p>

<script>
    window.onload = function() {
        var hour = new Date().getHours();
        if (hour < 12) {
          window.location.href = "http://xxx.example.com"
        } else {
          window.location.href = "http://yyy.example.com"
        }
    }
</script>

Solution 3 :

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
 window.onload = function() {
  var hour = new Date().getHours();
  window.location.replace(hour < 12 ? "http://xxx.example.com" : "http://yyy.example.com");
  }
 </script>

 </body>
</html>

Solution 4 :

Good place for a JS switch statement:

var hour = new Date().getHours(); 
var greeting = '';
var url = '';
switch(hour){
    case (hour < 12):
        url = "http://example1.com";
        greeting = "Good day";
        break;

    default: 
        greeting = "Good evening";
        url =  "http://example2.com";
}

document.getElementById("demo").innerHTML = greeting;
setTimeout(function(){ 
    window.location.replace(url);
    2000
);

Problem :

I’m trying to redirect a website based on a condition; if the hour is < 12 redirect to xxx.com, else redirect to yyy.com, i.e. merge this two pieces of code:

var hour = new Date().getHours();
var greeting;
if (hour < 12) {
    greeting = "Good day";
} else {
    greeting = "Good evening";
}
document.getElementById("demo").innerHTML = greeting;
<!DOCTYPE html>
<html>
  <body>
    <p id="demo"></p>
  </body>
</html>

and

window.location.replace("http://xx.com");

I’ve just started to learn js so any help is appreciated.

Comments

Comment posted by erutuf

Ah yes, thank you, that’s what I thought at first, and tried, but now I see it wasn’t working bc I was testing it in jsfiddle . Anyways, it works like a charm when ran properly.

By