Zeludon
Zeludon

Reputation: 45

How to make a html random redirect

How I would go about making a website that randomly redirects between multiple (in this case 2) websites?

Obviously what is below doesn't work due to what I hope is the meta tag; I would like to know if the javascript code is the correct way to do this and how it would work.

<head>
    <meta http-equiv="refresh" content="1;url=http://example1.com">
    <script type="text/javascript">
        if Math.random() =< 0.5;
          window.location.href = "http://example1.com/"
        else;
          window.location.href = "http://example2.com"
    </script>
    <title>Page Redirection</title>
</head>

Upvotes: 1

Views: 1606

Answers (3)

stwissel
stwissel

Reputation: 20384

You could make the function a little bit more generic:

  var sites = [
                        'http://www.dilbert.com',
                        'http://stackoverflow.com',
                        'http://Starwars.com'
                      ];
   var target = Math.floor(Math.random() sites.length);
    window.location = sites[target];

So when your site collection grows you don't need to alter the code. You could even pack it into a function:

       function goRandomSite(sites) {
             var target = Math.floor(Math.random() sites.length);
             window.location = sites[target];
              }

Hope that helps

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68413

your javascript syntax inside script tag is not correct either

<script type="text/javascript">
        if ( Math.random() <= 0.5 ) //proper parenthesis surrounding the condition and also < will come before =
          window.location.href = "http://example1.com/"; 
        else //semicolon removed from here
          window.location.href = "http://example2.com";
    </script>

Upvotes: 2

void
void

Reputation: 36703

You did it right (almost), Wrap the condition in () and remove ;, it will break the if.

if (Math.random() =< 0.5)
    window.location.href = "http://example1.com/";
else
    window.location.href = "http://example2.com";

Keep in mind one little fact.

if(false)
   alert(1);

Won't alert anyting as the if condition is always false. But if you see

if(false); // If will break here.
   alert(1);

Will always alert as if breaks and then the execution proceeds without if.

Upvotes: 1

Related Questions