Question

Can anyone see why my redirect isn't working? I've been through the forums and I can't see what I'm doing wrong. Please note the condition for the if statement is false. And the redirect should happen... Why isn't it?

<!DOCTYPE html>
<html>
<body>
    <p>Click the button to get a time-based greeting.</p>
    <button onclick="myFunction()">Try it</button>
    <p id="demo"></p>

    <script>
        function myFunction() {
            var x="";
            if (new Date("2014-03-04 21:00:00") < new Date()) {
                x="GOOD";
            } else {
                window.location = "http://www.google.com";
            }
            document.getElementById("demo").innerHTML=x;
        }
    </script> 
</body>
</html>

No correct solution

OTHER TIPS

Should be:

    window.location.href = "http://www.google.com";

Well, the code you have works in most browsers. If you are testing this in an old version of internet explorer, you might have to specify the standards. Try running it like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
    <p>Click the button to get a time-based greeting.</p>
    <button onclick="myFunction()">Try it</button>
    <p id="demo"></p>

    <script type="text/javascript">
    <!--
        function myFunction() {
            var x="";
            if (new Date("2014-03-04 21:00:00") < new Date()) {
                x="GOOD";
            } else {
                window.location.href = "http://www.google.com";
            }
            document.getElementById("demo").innerHTML=x;
        }
    // -->
    </script> 
</body>
</html>

I've updated the doctype as well as specified the script type. Also, use window.location.href instead of window.location, this will avoid the infinite loop a user might experiance trying to return to the previous page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top