jQuery - Redict to random site from text array after some time

62
May 19, 2017, at 6:55 PM

I have code like that

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

And i need a script wich grab one random link from textArray and href to it after some time.

Any ideas ? Thank You.

Answer 1

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

READ ALSO
Attach click event dynamically as below on document ready [on hold]

Attach click event dynamically as below on document ready [on hold]

The web page has 30 buttons and I loop 30 timesBut sometimes button 1 and 2 not working

64
Setting CSS class to a specific div with specific style attribute

Setting CSS class to a specific div with specific style attribute

I'm currently redoing a website (http://wwwvins-de-fronton

68
Using AJAX to Send Data on Button Click

Using AJAX to Send Data on Button Click

I have a table with multiple columns (indexphp)

92
How to format a number to currency R$, or $ to R$?

How to format a number to currency R$, or $ to R$?

How Can I format a simple number or $ format to Brazilian currency R$ - Real? I tried some ways to do this like maskMoney() plugin (I think that working just for inputs) but unsuccessfully

70