I’m trying to create a button on my website that opens a random page from a list in a new tab.
I think I’m pretty close, but when a new tab opens it is an "about:blank" page.
I’m not sure where I’m going wrong.
What I’ve tried is below
`<html lang="en">
<head>
<title>Redirect From List</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div style="text-align:center;padding:15px;">
<button style="text-align:center;" onclick="window.open()" type="button" name="" id="" class="btn btn-primary" btn-lg btn-block target="_blank">Random Website</button>
</div>
<script>
var links = [
"http://www.google.com",
"http://www.yahoo.com",
"http://www.bing.com",
"http://www.duckduckgo.com"
]
function openLink() {
var i = parseInt(Math.random() * links.length);
location.href = links[i];
}
</script>
</body>
</html>`
I’m using google, yahoo, bing, duckduckgo as placeholder websites, and I want it so that when I click the button, a random webpage from my Var Links list will open, so that I can update the URL’s as I add content.
However, right now, a new tab opens, but it doesn’t open any of the webpages from the list. Is there an error that I’m missing?
3
Answers
You need to assign openLink to your button.
right here
onclick="openLink()"
button style="text-align:center;" onclick="openLink()" type="button" name="" id="" class="btn btn-primary" btn-lg btn-block target="_blank">Random Website</button
You’re just opening a new blank window and then reloading the current window with another url!
But if you give the new window a variable name you’ll be able to reference it…
And then point to the new window before changing the url thus…
Below is working: