erutuf
erutuf

Reputation: 73

Redirect page using window.location.replace("xx"); based on a condition

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.

Upvotes: 2

Views: 2246

Answers (4)

Jamie_D
Jamie_D

Reputation: 999

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
);

Upvotes: 0

kelvin kantaria
kelvin kantaria

Reputation: 1448

<!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>

Upvotes: 0

ROOT
ROOT

Reputation: 11622

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>

Upvotes: 1

Radu Diță
Radu Diță

Reputation: 14171

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>

Upvotes: 4

Related Questions