Energizer7 Energizer7 -4 years ago 117
HTML Question

Redict to random site from text array after some time

I have code like this:

jQuery(document).ready(function() {
var textArray = [
'www.google.com',
'www.stackoveflow.com'
];
var randomNumber = Math.floor(Math.random()*textArray.length);

link.setAttribute('src', textArray[randomNumber]);

setTimeout(function(){
window.location = link;
}, 1000);
});


I need a script which grabs one random link from
textArray
and redirects the user to it after a delay. How can I do that?

Answer Source

Your logic is almost correct, you just have two issues. Firstly, you need to use absolute URLs when redirecting, so add http:// to the links.

Secondly, link needs to be a string so that you can provide it to window.location. Therefore it will not have a setAttribute function. You can just set it equal to the random value from the textArray. Try this:

var textArray = [
  'http://www.google.com',
  'http://www.stackoverflow.com'
];
var randomNumber = Math.floor(Math.random() * textArray.length);
link = textArray[randomNumber];

setTimeout(function() {
  window.location.assign(link);
}, 1000);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download