Juninho10
Juninho10

Reputation: 23

Open a random page using JavaScript

I'm newbie, I'm trying to create a redirect.html page which will send a visitor to a random site as soon as he open the redirect page. Please help to edit the following code, I think the issue is in this line:

"echo "<meta http-equiv='refresh' content=0;URL="openLink();">"

<html>
<head>
<script type="text/javascript">
<!--
// Create an array of the links to choose from:
var links = new Array();
links[0] = "http://www.google.com/";
links[1] = "http://www.bing.com/";
links[2] = "http://www.yahoo.com/";
links[3] = "http://www.apple.com/";

function openLink() {
  // Chooses a random link:
  var i = Math.floor(Math.random() * links.length);
  // Directs the browser to the chosen target:
  parent.location = links[i];
  return false;
}
//-->
</script>
</head>
<body>
echo "<meta http-equiv='refresh' content=0;URL="openLink();">
</body>
</html>

Upvotes: 0

Views: 8258

Answers (2)

bnoeafk
bnoeafk

Reputation: 539

First of all, the section and not in the (basically placed in a tag before any information is returned to the browser).

Secondarily, using the META tag isn't the best format to use these days but if you have to use it : you can use Javascript to build a META tag, using something like :

<script type="text/javascript">
var urls = new Array("http://www.google.com/", "http://www.yahoo.com/");

function redirect()
{
    window.location = urls[Math.floor(urls.length*Math.random())];
}
var temp = setInterval("redirect()", 3000);
</script>

But, as per your code, remove the openLink() call from the META tag and place it on the onload:

<html>
<head>
<script type="text/javascript">
<!--
// Create an array of the links to choose from:
var links = new Array();
links[0] = "http://www.google.com/";
links[1] = "http://www.bing.com/";
links[2] = "http://www.yahoo.com/";
links[3] = "http://www.apple.com/";

function openLink() {
  // Chooses a random link:
  var i = Math.floor(Math.random() * links.length);
  // Directs the browser to the chosen target:
  parent.location = links[i];
  return false;
}
//-->
</script>
</head>
<body onload="openLink();">
</body>
</html>

Upvotes: 2

Leonard
Leonard

Reputation: 3092

You can't attach javascript functions to the meta tag. Put your openLink() call on the tag, alternatively within the body of the page.

<body onload="openLink();">

Upvotes: 1

Related Questions