I have some code that’ll allow me to open up a random website from a list of websites but I’d like to open each one up in a new tab, how do I do this?
Information you may need
the code
JavaScript
x
38
38
1
<html>
2
<button onclick="randomLink();OpenInNewTab();">Click here to go somewhere else! </button>
3
4
<script type="text/javascript">
5
6
7
var randomLink = function () {
8
9
// first create an array of links
10
var links = [
11
"bbc.com",
12
"google.com",
13
"youtube.com",
14
"facebook.com"
15
];
16
17
// then work out the maximum random number size
18
// by counting the number of links in the array
19
var max = (links.length)
20
21
// now generate a random number
22
var randomNumber = Math.floor(Math.random()*max);
23
24
// use that random number to retrieve a link from the array
25
var link = links[randomNumber];
26
27
// change the location of the window object
28
window.location = "http://" + link;
29
30
// Opens a new tab.
31
function OpenInNewTab(url) {
32
var win = window.open(url, '_blank');
33
win.focus();
34
}
35
}
36
</script>
37
</html>
38
I tried doing the action in question at two different points and hope you’re input can help to correct this.
Location 1
JavaScript
1
2
1
<button onclick="randomLink();OpenInNewTab();">Click here to go somewhere else!
2
Location 2
JavaScript
1
5
1
// Opens a new tab.
2
function OpenInNewTab(url) {
3
var win = window.open(url, '_blank');
4
win.focus();
5
The following web address is what the code currently looks like and does.
*EDIT : The only changes I made are the websites.They’re much more on the live demo.
Advertisement
Answer
The code you wrote is wrong, since you change the address of the current window (via the line window.location=...
, and other issues… but here:
Working example fiddle
Very similar, and works.
Code
HTML
JavaScript
1
2
1
<button onclick="openStuff();">Click here to go somewhere else!</button>
2
JS
JavaScript
1
18
18
1
// the used links
2
var links = [
3
"bbc.com",
4
"google.com",
5
"youtube.com",
6
"facebook.com"];
7
8
openStuff = function () {
9
// get a random number between 0 and the number of links
10
var randIdx = Math.random() * links.length;
11
// round it, so it can be used as array index
12
randIdx = parseInt(randIdx, 10);
13
// construct the link to be opened
14
var link = 'http://' + links[randIdx];
15
// open it in a new window / tab (depends on browser setting)
16
window.open(link);
17
};
18