How to make HTML onclick event buttons trigger one of two different functions at random?

How to make HTML buttons onclick randomly run one of two different functions in random order?

I am using PHP on the server and jQuery on the client. Using this code, when I click the button, nothing happens ...

 function a(){ alert('A got called!'); } function b(){ alert('B got called!'); } $('#button').bind('click', function(){ var rnd = Math.floor(Math.random() * 2); if(rnd) a(); else b(); }); 

.........

 < "base_url().'images/free.png';" rel="nofollow" border='0' align='center' alt="FREE" id="button" /> 
+4
source share
5 answers
 $('button').bind('click', function(){ var rnd = Math.floor(Math.random() * 2); if(rnd) AnswerForEverthing(); else WhatAmountOfWoodWouldAWouldchuckChuck(); }); 
0
source

As John said, attach one function to the onclick button, then this function will call one of your two functions randomly.

In jQuery you can do it like this:

 function a(){ alert('A got called!'); } function b(){ alert('B got called!'); } $('#your_buttons_id_attribute').click( function(){ var functions = [a,b]; var index_of_function_to_call = Math.round(Math.random()); functions[index_of_function_to_call](); } ); 
+5
source

Say you have the code:

 $('#button').click(function() { // handler 1 code }); $('#button').click(function() { // handler 2 code }); 

You would change it to:

 $('#button').click(function() { if(Math.random() < 0.5) { // handler 1 code } else { // handler 2 code } }); 
+3
source

Attach one event handler and make this one handler to decide what to do randomly.

For example, in C # you can:

 private readonly Random rng = new Random(); ... button.Click += TakeRandomAction; ... private static void TakeRandomAction(object sender, EventArgs e) { if (rng.Next(2) == 0) { GiveUserPony(); } else { NukePlanetFromOrbit(); // It the only way to be sure } } 

Details may vary in jQuery / JavaScript, but basically you should still make an onclick call to one function, which then worked out what to do.

+2
source
 function randomFunction() { var args = arguments; return function() { args[Math.floor(Math.random()*args.length)](); }; } $('#id').click(randomFunction(functionOne, functionTwo)); 

Not tested, hope it works. How it works: randomFunction returns a function that itself calls one of the randomFunction arguments.

This approach obviously only makes sense if you have multiple events and you need a random function to answer them. If this is just one single event than using one of the most versions above is easier.

0
source

All Articles