Ways to shuffle elements on a webpage randomly?

Currently, I am teaching myself HTML, CSS, and JavaScript and experimenting with building something interesting.

I have a vision of creating 100 clickable images/links (essentially buttons featuring the same image). I want a certain percentage of these buttons to direct users to one page, while the rest lead to another page. The user would not know this until they click on a button.

Every time the page is reloaded, I desire the placement of the images/links to be randomized.

Although I am aware that I can generate random numbers in JavaScript using Math.random(), I am struggling to implement the concept described above. As I believe in learning by doing, I wondered if anyone could provide me with some guidance.

Answer №1

document.addEventListener('DOMContentLoaded', function() {
    for(let j=0;j<50;j++)
        GenerateButtons();
});

function GenerateButtons()
{
    let button = document.createElement("BUTTON");   // Creating a new <button> element
    button.innerHTML = "Test your fate";                   // Adding text

    button.onclick = OpenLink;
    document.body.appendChild(button);  
}

function OpenLink()
{
    let redirectPage = "";
    let randomNum = Math.random();
    if(randomNum % 2 == 0)
        redirectPage = "https://www.example.com/page1";
    else
        redirectPage = "https://www.example.com/page2";
    window.location.replace(redirectPage);
}

GenerateButtons() will generate a collection of buttons on the page, and each time a button is clicked, OpenLink() will randomly select where to redirect the user.

Here are some resources I used to help with this solution: https://www.example.com/page1 https://www.example.com/page2

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

Error: You forgot to close the parenthesis after the argument list / there are duplicate items

I have already tried to review a similar question asked before by checking out this post, but unfortunately, I still couldn't find a solution for my problem. Even after attempting to add a backslash (\) before the quotation mark ("), specificall ...

Maintain the image's aspect ratio by setting the width equal to the height when the height is

I am uncertain if achieving this purely with CSS is possible, but it would be ideal. I currently have an image: <img src="#" class="article-thumb"> CSS: .article-thumb { height: 55%; } Is there a way to set the width equal to the height? My g ...

Is create-react-native-app experiencing functionality issues?

As someone who is new to expo and create-react-native-app, I recently encountered a strange issue while learning react-native. Normally, I use create-react-native-app without any problems. However, one day when I tried to create a new project, I was presen ...

What is the best way to alter the background of a div when hovering over a button in a separate div?

Looking to change the background of one div when hovering over a button in another div? Hello, I have a task where I need to modify the background color of a specific div when a button below it is hovered over. The setup involves having an image (a tshir ...

Ways to enhance the Response in Opine (Deno framework)

Here is my question: Is there a way to extend the response in Opine (Deno framework) in order to create custom responses? For instance, I would like to have the ability to use: res.success(message) Instead of having to set HTTP codes manually each time ...

Ways to have form inputs dynamically increase in value and then send the data via a post request

I've tried various methods to achieve the desired outcome but haven't had any luck. My goal is to have the innerHTML from the JavaScript below displayed a certain number of times, based on the dropdown selection, and then submit all fields to ano ...

Unlock the full potential of Angular Material Framework by leveraging Custom Palettes

I'm experiencing some issues implementing Custom Palettes with Angular Material Framework. I'm still trying to grasp the concept of using a custom theme. In the Angular configuration file. $mdThemingProvider.definePalette('crmPalette' ...

Tips for uploading a photo in Selenium Webdriver using Java when the input type is not 'File'

<span> <span class="glyphicon glyphicon-plus avatarUploacIcon"></span> Upload profile image</span> Here is the code I am currently using: WebElement uploading=driver.findElement(By.cssSelector("div[class='form_advanced_wrapp ...

Unit testing is encountering issues due to errors with objects not being accepted as a React child component

Here is the code where I am testing the functionality of mytestFunc when a checkbox is checked. Checkbox - <input id="mycheck" type="checkbox" onClick={this.mytestFunc} /> mytestFunc function - mytestFunc = e => { const mockdata = this.stat ...

The instance cannot be accessed by ES6 class methods

Having trouble accessing the this instance in one of my methods within a class that I created. In my router, I am calling the method like this: import Emails from '../controllers/emails' import router from 'express' .... route.post(&a ...

Unable to submit the form to the PHP script

One of the techniques I used recently was AJAX for handling a form submission. I created a simple example to demonstrate the JavaScript code I utilized in this scenario. If the form is successfully submitted, no alert will be shown to the user. However, i ...

What can I do to resolve the problem with td border

Check out my website over at browsethewebclean.com I've come across a peculiar issue with the borders and background color of some nested tables on my page. It seems that the border is not aligning properly and the background color goes beyond the im ...

Console builds successfully, but encountering issues with building in Docker

Whenever I compile my vite image locally using the following command (found in package.json): "vite_build:dev": "NODE_ENV=test env-cmd -f ./config/.env.dev react-scripts --max_old_space_size=8000 build", everything functions correctly ...

Converting a JavaScript map into an array with ES6: A step-by-step guide

I am in need of a solution to convert a JavaScript map into an array with a specific format: [ { name: "21 years old", totalUsers: 2, }, ... ] For example, if I have the following map: const ages = { "21": 2, "18 ...

Generate a consolidated dataframe by parsing through various HTML files

I have a collection of 23 HTML files that all contain data in the same tabular format. I am looking to combine this data into one large dataframe for further analysis. Below is the code snippet I am using: import glob import pandas as pd all_records = g ...

Obtain the selected option's value using Angular

Having an issue with my user.model.ts file. I have a list of users that I can edit by clicking on a button that filters the user's data and puts it in a bootstrap modal. I'm using [ngModel] in a select tag to get the country of my user, but when ...

Styling limitations encountered when using lang="scss" with scoped css

My current project involves using Quasar and I am attempting to style the first column of q-table: <style lang="scss" scoped> td:first-child { background-color: #747480 !important; } </style> Unfortunately, this code does not seem to have a ...

How can I utilize passed in parameters in Meteor React?

I am trying to figure out how to use two params that I have passed in the following example. Can someone please assist me? updater(layer, item){ this.setState({layer5: <img id="layer5" className="on-top img-responsive center-block" name="layer5" ...

Encountered an issue during deployment with Vercel: The command "npm run build" terminated with exit code 1 while deploying a Next.js web application

I've been working on a local Next.js app, but encountered an error when deploying it. Vercel Deployment Error: Command "npm run build" exited with 1 Here is the log from the build process: [08:26:17.892] Cloning github.com/Bossman556/TechM ...

Issue with .submit() not submitting form after setTimeout timer runs out

How can I add a delay after a user clicks submit on a form before it actually submits? I have an image that appears when the click event is triggered, but the form never actually submits... This is the HTML form in question: <form class='loginFor ...