Link to a completely random webpage

I am looking to add a randomization feature to my collection of 30 HTML pages. When a user clicks on a button, I want one of the 30 pages to be displayed randomly.

I have come across some scripts online that claim to achieve this, but they seem a bit messy and complicated. I'm curious if there is a simpler, cleaner solution out there?

Appreciate any help!

Answer №1

If your array was named arr, you could easily retrieve a random value with this code snippet:

var value = arr[Math.floor(Math.random() * arr.length)];

This code will generate a random number within the range of 0 to the length of your array.

You can then direct the user to the generated URL using the following JavaScript:

window.location = value;

Testing out the Code

We have created a simple demonstration on JSFiddle: http://jsfiddle.net/ESSAc/1/

In the demo, there is a button with an onclick attribute that executes the function when clicked:

<input type="button" onclick="runme()" value="Click Me!" />

The function defined in the script randomly selects a URL from an array and displays it in an alert box:

function runme() {
    var arr = ["http://www.bbc.co.uk/", "http://www.yahoo.com/", "http://www.stackoverflow.com/"];
    var value = arr[Math.floor(Math.random() * arr.length)];
    alert("Would navigate to : " + value);
    // window.location = value;     // Uncomment this line to actually navigate
}

Answer №2

When approaching this problem, I tend to follow a similar approach:

jQuery('#button').on('click', function() {
    jQuery.getJSON(
        'random-url-generator.php',
        function(response) {
            window.location.href = response.url;
        }
    );
});

It's important to also maintain an array of pages on the server side for easy access.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to handle this unconventional JSON structure?

Looking for some insight on retrieving process information from a VPS with PM2. However, the JSON string returned by PM2 is malformed, making it impossible to run JSON.parse(). An example of the output provided by PM2: '{data: 0, informations: " ...

Guide to showing MySQL data on an HTML page using NodeJS

Currently delving into Node JS, I am faced with the challenge of displaying fetched data from my MySQL Table in an HTML table format. Despite my efforts, I have yet to find a solution that works for me. Any help or guidance on how to resolve this issue wou ...

Utilizing J Query and AJAX to retrieve user details through API without the need for page refresh

I'm new to using Ajax and Jquery. 1) When I try to add a new user using the post method through a form within an HTML Modal, the Modal doesn't automatically close upon clicking the Submit button. I end up having to refresh the page to see if the ...

Tips for concealing the boundary lines within a Polararea chart utilizing vue-chartjs

I am currently working on a project that involves a polararea chart using vue-chartjs and I am facing an issue with hiding the 'area lines' (the circle ones) and the percentage numbers on them in this chart. Unfortunately, I couldn't find an ...

Mongo sometimes fails to provide accurate results

My nodeJS script is designed to process queued JSON requests. It starts by querying Mongo (v3.6.3) for a queue of requests and then iterates through each request using forEach. The API endpoint is queried using promises and async/await to parse the request ...

npm allows for multiple entry points for modules

I'm working on an NPM package and I'm curious about how to allow users to register multiple entry points. This way, they have the option to import either the entire library or just specific parts that they need. For instance, importing the compl ...

The length property of a jQuery array may not always match the actual length of the array

Recently delving into jquery, I encountered the issue described in the title. Below is an excerpt from my controller code: [HttpPost] public JsonResult getProjectList() { List<Project> projectList = new List<Project>(); ...

Printing from a Windows computer may sometimes result in a blank page

Looking to incorporate a print button into an HTML page, I'm facing an issue. The majority of the content on the page should not be included in the printed version, so my approach involves hiding everything in print and then showing only the designate ...

Is it possible to programmatically close all React Native modal alerts and dialogs?

When our app receives an unauthorized response from one of our API calls, we automatically redirect the user to the login screen. This action can occur at any time due to background refreshes triggered by web sockets, among other factors. The challenge lie ...

Angular Group Formation Issue

I keep encountering the following error: formGroup expects a FormGroup instance. Please pass one in. This is how it looks in HTML: <mat-step [stepControl]="firstFormGroup"> <form [formGroup]="firstFormGroup"> And in my Typ ...

Switching Tabs When a Button is Clicked

I am currently using a guide from the link provided to learn how to create tabs: http://www.w3schools.com/howto/howto_js_tabs.asp. function openTab(evt, tabName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClass ...

Experiencing problems with geolocation feature policy while working with Ionic framework

Currently, I have integrated Google maps into my Ionic project using the code snippet below: this.geolocation.getCurrentPosition().then((position) => { let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); let ...

There is no response from Ajax

I am facing an issue with my AJAX call in communication with my Rails controller. Even though the AJAX call itself seems fine, the callback function does not contain any data. Here is the AJAX request I'm making: $.ajax({ url: '/get_progres ...

Creating a Vue.js vuetify input that restricts the user to entering only three digits before the decimal point and two digits after the decimal point

I am looking to implement a restriction on the total number of input digits to 3. Users should be able to enter numbers like 333, 123, etc. However, if they include a decimal point, they should only be allowed to enter 2 digits after the decimal point. Val ...

"The transparency of the three-js canvas texture is compromised when using the WebGL renderer, unlike the Canvasrenderer which maintains

I am attempting to display a CircleGeometry over a cube from the camera view. The cube has a solid color, while the circle contains just an arc on a canvas with no background color. When using CanvasRenderer, the transparency of the canvas is retained an ...

The property express.json() is not recognized

Why doesn't Typescript recognize the express.json() function, even though many tutorials claim it should compile without errors? Could I have overlooked something in my code? An example tutorial that suggests this code works: https://auth0.com/blog/n ...

Looking to transfer the name of the clicked link to a modal in order to execute a PHP/SQL query within the modal window

I am currently utilizing Twitter Bootstrap's modal feature. Within my table, I am mapping MAC addresses to vendor names using the following code: <tbody> <?php foreach ($rowarr as $k => $v) { ?> & ...

What is the best way to delete a specific date from local storage using Angular after saving it with a key

I'm attempting to clear the fields in my object (collectionFilter) from local storage using localStorage.removeItem('collectionFilter'). All fields are removed, except for the date fields. Please note that I am new to JavaScript and Angular. ...

How to retrieve attributes of a model from a related model in Sails.js

Currently, I am utilizing the beta version(v0.10.0-rc3) of Sails.js and have updated the database adapter to PostgreSQL in order to enable associations via the Waterline ORM. My main focus is on creating a role-based user model for authorization based on d ...

Implementing an automated numbering system in Typescript to assign a unique id attribute to every object within an array

I am currently dealing with an array of objects: myArray = [ { "edoId": "4010", "storeName": "ABBEVILLE" }, { "edoId": "3650", "storeName": "AGEN" }, { ...