In JavaScript, a button is programmed with a rare 1.04% probability of directing to Page A and a much higher 98.96% likelihood of redirecting to Page

My goal is to create a button that, when clicked, will have a 1.04% probability of navigating to Page A and a 98.96% chance of going to Page B. The challenge I'm facing is in randomizing these results using JavaScript. I am fairly new to this language so any assistance would be greatly appreciated.

--edit-- I am integrating this code into a project on Wix, and below is the complete code I have developed so far. Initially, I used simple whole numbers like 40/60 to ensure functionality, but I am struggling with implementing the smaller percentages such as 1.04 instead of 1.00.

import wixLocation from 'wix-location';
let random = 0, counter40 = 0, counter60 = 0;

$w.onReady(function () {
 for (var i = 0; i < 10000000; i++) {
    random = Math.floor((Math.random() * 100) + 1);
    if (random <= 40)   {
        counter40++;
    } else {
        counter60++;
     }
  }
  console.log("counter40: " + counter40.toString());
  console.log("counter60: " + counter60.toString());
});

export function button1_click(event) {
    random = Math.floor((Math.random() * 100) + 1);
    if (random <= 40)   {
        wixLocation.to("/pageB");
    } else {
        wixLocation.to("/pageC");
   }
}

Answer №1

Visit this link to see the code in action!

Here's the HTML code:

<button id="randomRedirect">
  Press me
</button>

And here's the JS code:

let button = document.getElementById('randomRedirect')
button.addEventListener('click', function() {
  let randomNum = Math.random();
  if (randomNum < 0.9896)
    window.location.href = "pageB.html";
  else
    window.location.href = "pageA.html";
}, false);

Answer №2

One way to introduce randomness is by using the Math.random() function, which generates a random number within the range of 0 and 1.

x = Math.random()
if(x < 0.0104){//There's a 1.04% chance
  window.location.href = [Page A]
}
else{
  window.location.href = [Page B]
}

Answer №3

The built-in function in JavaScript that generates random values is Math.random().

It produces a decimal number ranging from 0 to 1.

If you want a probability of 1.04%, you can achieve it by executing the following code:

let chance = Math.random() <= 0.0104;

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

Using Node.js setTimeout method

I'm struggling with understanding how to utilize the setTimeOut function in NodeJS. Let's say I need: function A() to be executed every 10 seconds. If function A returns 'true' from its callback, it should trigger a call to a specific ...

Standardize all values for each key in sub-dictionaries and include them as additional key-value pairs

Suppose there is a dictionary containing nested sub-dictionaries: let dict = { "SEATTLE" : { "gross_sales" : 106766, "price" : 584.50, "dates" : [ { " ...

I encountered an issue in ReactJS where I received a TypeError stating that props.history.listen is not a function

Why is this showing up? I'm using ReactJS and can't figure out what's going wrong. Here is my history.js: import { createBrowserHistory } from 'history' export default createBrowserHistory In my App.js: import React from 'r ...

What is the best way to display a single div at a time?

I have a setup with three sections, each containing two divs. The first div has a button that, when clicked, should open the next div while closing any other open div. However, I am facing an issue where clicking the button again does not close the corresp ...

Turn the Array by k Positions

How can we rotate an array k times given an array and a number k? Sample Input 1 //number of of testcases 5 2 //5(array size) 2(K value) 1 2 3 4 5 /array elements Sample output 4 5 1 2 3 Here is the code snippet: import java.util. ...

Searching for the closest jQuery value associated with a label input

As a beginner in JQuery, I am looking to locate an inputted value within multiple labels by using a Find button. Below is the HTML snippet. Check out the screenshot here. The JQuery code I've attempted doesn't seem to give me the desired output, ...

Using track by in ng-repeat function triggers an endless $digest-loop issue

It appears that I am still struggling to grasp the mechanism behind ng-repeat, $$hashKeys, and track by. Currently, in my project, I am working with AngularJS 1.6. The Issue: I have an array of complex objects that I want to display as a list in my view ...

How to retrieve the value of input in a Formik form when the onChange event occurs

Currently, I am working on creating a form using React JS and the Formik library. One issue I encountered was related to validation, specifically the need to replace invalid letters with an empty string. str.replace(/\D/, ''); The challenge ...

Using jquery.ajax to post to a single page without passing any variables

In order to capture the onclick event for a specific #id, I am retrieving form data and checking if $_POST['submit'] is set. If it is, I proceed to send an email. Although there are no errors, it appears that no data is being sent via post. < ...

An AJAX event handling function returns a null value upon invocation

Recently, I've been working on a function named 'getAuthor' which includes an AJAX event. Here's the code snippet: function getAuthor(id){ $.get('http://www.connectnigeria.com/articles/wp-json/wp/v2/users/74',function(e){ ...

Efficiently Create C# Sub-Arrays without Copying or Allocating Memory

In C#, can a temporary sub-array be created on top of an existing array without any memory allocations or copying? ...

Tips on updating service variable values dynamically

I need to update a date value that is shared across all controllers in my website dynamically. The goal is to have a common date displayed throughout the site by updating it from any controller and having the new value reflected on all controllers. Can yo ...

Retrieve form data (from a standard form submission) with jQuery

Within page A, I have a form containing 2 fields - one for the user and one for the password. The form's action directs to page B. Is there a way to use JavaScript to retrieve the form values from the request header when page B is loaded? Or is there ...

Display intricate header and preview in a printed datatable

Hey there, I've been using the Datatable plugin and it's really great. However, I've come across a problem with complex headers like this: <thead> <tr><td>some text</td></tr> <tr><td>some te ...

Are you looking to receive specific and organized pages of data from DynamoDB?

In my react-native project, I am utilizing DynamoDB along with NodeJS on the server-side. The table in question has a primary key of 'hashtag' and a sort key of 'timestamp'. hashtag | timestamp blabla | 1 blabla | 2 blabla | 3 bla ...

Having issues with IE8 and SmoothGallery script errors

I'm currently utilizing the SmoothGallery plugin created by Jon Designs to enhance the website of one of my clients. However, there seems to be a minor issue in Internet Explorer 8 when attempting to navigate to the next image. Interestingly enough, a ...

undefined is causing an error in React

Trying to display information on the UI, I am checking the status of IsMobileOnLease which is a child node in JSON. However, I am encountering an error that says "cannot read property of undefined react". If (this.mob.MobileLobList[0].MobileRiskList[0].I ...

Strategies for transferring data from JavaScript to Express for seamless integration as a default value

I am currently utilizing express, MongoDB for the database, and EJS. I am in the process of developing a form that allows users to submit a new article for a blog. The goal is for the website to redirect back to the page with the form fields populated if a ...

The Vue component appears to be missing from the HTML code

I recently began learning Vue.js in school, and for my first assignment I need to print a h2 from a Vue component. However, I am having trouble getting it to work. Below is the code for the Vue component that I have created. var app = new Vue({ ...

Best practices for timeout in HTTP long polling

As an avid user of Javascript AJAX and long-polling, I am constantly seeking the best value for server response timeout. Despite scouring numerous documents, a detailed explanation for timeout continues to elude me. Some suggest 20 seconds, while others ...