+ 4
How to create random link in html or JavaScript
I want to show random link like one time google.com,then yahoo.com,then Wapka.com,then again google.com
5 Respuestas
+ 7
<a href="#" onclick="randSite();">Random</a>
var arr = ["google.com",
"youtube.com", "markfoxx.com",
"codednations.com"];
function randSite(){
location.href = "http://" + arr[Math.floor (Math.random()*arr.length)];
}
Try to reduce lines of code as much as possible... This would be a cool feature if you had a server side language return or fill the array with values - returned back in JSON format or a standard array. I say this because you wouldn't have to keep adding new values to the array or this script manually, so it's completely dynamic.
+ 2
In the JavaScript file, store the random links in an array, then use JavaScript random function to choose and return a random link from the array. Enclose it in a function, then, in your HTML file, call the function on click. Profit.
+ 2
To acompany what Oriana just said here is an example
<a href="javascript:openSite()">Click to go to a random site</a>
<script>
var links = [
"google.com",
"youtube.com",
"reddit.com",
"apple.com"]
var openSite = function() {
// get a random number between 0 and the number of links
var randIdx = Math.random() * links.length;
// round it, so it can be used as array index
randIdx = parseInt(randIdx, 10);
// construct the link to be opened
var link = 'http://' + links[randIdx];
return link;
};
</script>
+ 2
Indeed Mark, I just made it longer for readability thought yours is shorter and more speed and better optimized.
0
Thank You @simen it works by opening a page with just the text of the random site from list .
How do you get it to actually open the page in a new tab ?