0

I'm trying to create a button that links to random websites like on 'The useless web'. I found this code on here and it's worked almost perfectly. I just need help making the sites open in a new tab, at the moment they change the current window. Any help will be greatly appreciated. THANKS

CURRENT:

<script type="text/javascript">
var urls = [
    "http://www.kittenwar.com/",
    'http://heeeeeeeey.com/',
    'http://cat-bounce.com/'
];

function goSomewhere() {
    var url = urls[Math.floor(Math.random()*urls.length)];
    window.location = url; // redirect
}

onClick handler assigned:

<a href="#" onClick="goSomewhere(); return false;">Gimme something weird!</a>
  • already answered here, I believe - https://stackoverflow.com/questions/4907843/open-a-url-in-a-new-tab-and-not-a-new-window -- so as not to be evasive, you really can't do it this way, from javascript. You could put it on the page in an HTML form, have the form target be something new, and have javascript submit the form though! –  Apr 13 '20 at 19:04
  • Add target="_blank" to your link https://stackoverflow.com/questions/34082002/html-button-opening-link-in-new-tab/46542656 – Seth McNaughton Apr 13 '20 at 19:07
  • @SethMcNaughton - there is no link, at least not yet! Otherwise, I think you have the right idea. At least in this example it's all js. –  Apr 13 '20 at 19:08

2 Answers2

0

use this function

 function goSomewhere() {
        var url = urls[Math.floor(Math.random()*urls.length)];
        window.open(url, '_blank')
    }
mr. pc_coder
  • 16,412
  • 3
  • 32
  • 54
0

To open a page in a new tab, you should create the button like this:

<button href='w3schools.com' target='_blank'>Click me!</button>

You can change the href tag with JavaScript.