+ 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

11th Mar 2017, 5:47 PM
Rakesh Kumar
Rakesh Kumar - avatar
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.
11th Mar 2017, 7:09 PM
Mark Foxx
Mark Foxx - avatar
+ 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.
11th Mar 2017, 5:59 PM
Winderine
Winderine - avatar
+ 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>
11th Mar 2017, 6:10 PM
Simen Daehlin
Simen Daehlin - avatar
+ 2
Indeed Mark, I just made it longer for readability thought yours is shorter and more speed and better optimized.
11th Mar 2017, 7:11 PM
Simen Daehlin
Simen Daehlin - avatar
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 ?
16th Oct 2023, 8:07 AM
Joseph Keegan