Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I open up a random url from a list of url's in a new time each time it is clicked?

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

    <html>
    <button onclick="randomLink();OpenInNewTab();">Click here to go somewhere else!    </button>

    <script type="text/javascript">


    var randomLink = function () {

        // first create an array of links
        var links = [
            "bbc.com",
            "google.com",
            "youtube.com",
        "facebook.com"
        ];

        // then work out the maximum random number size
        // by counting the number of links in the array
        var max = (links.length)

        // now generate a random number
        var randomNumber = Math.floor(Math.random()*max);

        // use that random number to retrieve a link from the array
        var link = links[randomNumber];

        // change the location of the window object
        window.location = "http://" + link;

        // Opens a new tab.
        function OpenInNewTab(url) {
        var win = window.open(url, '_blank');
         win.focus();
}
    }
    </script>
</html>

I tried doing the action in question at two different points and hope you're input can help to correct this.

Location 1

<button onclick="randomLink();OpenInNewTab();">Click here to go somewhere else!

Location 2

// Opens a new tab.
function OpenInNewTab(url) {
var win = window.open(url, '_blank');
win.focus();

The following web address is what the code currently looks like and does.

  • http://holyshitthisisalotofuselesscraponotherwebsites.com/

*EDIT : The only changes I made are the websites.They're much more on the live demo.

like image 485
flyinggoatman Avatar asked Dec 07 '25 23:12

flyinggoatman


1 Answers

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

<button onclick="openStuff();">Click here to go somewhere else!</button>

JS

// the used links
var links = [
    "bbc.com",
    "google.com",
    "youtube.com",
    "facebook.com"];

openStuff = 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];
    // open it in a new window / tab (depends on browser setting)
    window.open(link);
};
like image 74
Matyas Avatar answered Dec 09 '25 13:12

Matyas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!