views:

444

answers:

6

How do I make an HTML button’s onclick event trigger one of two different functions at random?

I’m using PHP on the server, and jQuery on the client. Using this code when i click the button image 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"   />
+3  A: 

Attach one event handler, and make that single handler decide what to do randomly.

For example, in C# you might do:

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's the only way to be sure
    }
}

The details may vary in jQuery / JavaScript, but basically you'd still make onclick call a single function which then worked out what to do.

Jon Skeet
hmm do you have an example i can explore? Edit:ok just saw it. Something with PHP?
JEagle
@JEagle: Which bit of it is giving you difficulties? Do you know how to generate a random number? Do you know how to call one function from another?
Jon Skeet
+1 for the nuking.
GenericTypeTea
@ Jon Skeet. I have the 2 onclick working independently. My worry is how to add them to the same button.
JEagle
@JEagle: Read Jon's answer carefully: *Attach **one** event handler, and make **that single handler** **decide what to do randomly** .*
Felix Kling
I can't find a `C#` tag in this question anywhere.
jAndy
@Felix, Sorry to be asking those questions, i'm still a newbie on this Jquery thing. Will try to look for on how to do that
JEagle
@JEagle: Imagine that your two existing handlers are GiveUserPony and NukePlanetFromOrbit in my example: we're attaching one event handler which calls one of the others, randomly.
Jon Skeet
@jAndy: When I answered the question, there was no indication whatsoever of what platform was involved. However, I left the answer as it was after the tags were added because the *approach* would be the same regardless of platform.
Jon Skeet
A: 

Wouldn't this work: (untested)

<?php

$script = <<<EOD 
    <script type="text/javascript">
         $( ".id" ).click( function( evt ){ handler1( evt ); handler2( evt ); } )
    </scipt>
EOD;
echo $script;

?>
Christopher W. Allen-Poole
That will just call both handlers. The OP asked to call one randomly.
sje397
A: 
$('button').bind('click', function(){
    var rnd = Math.floor(Math.random() * 2);
    if(rnd)
       AnswerForEverthing();
    else
       WhatAmountOfWoodWouldAWouldchuckChuck();
});
jAndy
I’m quibbling here (and possibly just misunderstanding the code, it’s early), but wouldn’t that call `AnswerForEverthing` 25% of the time, and `WhatAmountOfWoodWouldAWouldchuckChuck` 75% of the time? In other words, it’s not quite as random as it could be.
Paul D. Waite
@Paul D. Waite: No, that behavior would happen if you multiply the result from `Math.random()` by `3`.
jAndy
@jAndy: Ah! Yes, sorry, Math.floor, gotcha.
Paul D. Waite
been trying the several code examples but when i remove the onclick and put instead the id="button" i can't have it working anymore...
JEagle
@JEagle: working example: http://www.jsfiddle.net/ptjp2/
jAndy
@jAndy, Ok it works. Now how can i make it work with this line: <img src="<?php echo base_url().'images/free.png';?>" rel="nofollow" border='0' align='center' alt="FREE" /> . I tried to put there id="button" but it doesn't work...
JEagle
@JEagle: you most likely forgot to set the `jQuery selector`. You need to select by `$('#button')` to match an element with the `ID` = `button`. See http://www.jsfiddle.net/ptjp2/1/
jAndy
I had it already like: <img src="<?php echo base_url().'images/free.png';?>" rel="nofollow" border='0' align='center' alt="FREE" id="button" /> but still no luck... What's going on?
JEagle
@JEagle: just add a `#` before the word `button` :)
jAndy
doh! It's working. Thanks jAndy! and everyone that helped.
JEagle
+3  A: 

Say you have code like:

$('#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
  }
});
sje397
+5  A: 

As Jon said, attach one function to the button’s onclick event, then have that function call one of your two functions randomly.

In jQuery, you could 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]();
    }
);
Paul D. Waite
If you're going to bother with an array, then maybe you should use `Math.round(Math.random() * functions.length)`
sje397
@sje397: Oh aye, that would be better. I think you'd need Math.floor as opposed to Math.round (see jAndy's answer below). I prefer your approach as it's simpler.
Paul D. Waite
A: 
function randomFunction() {
    var args = arguments;
    return function() {
        args[Math.floor(Math.random()*args.length)]();
    };
}

$('#id').click(randomFunction(functionOne, functionTwo));

Haven't tested, hope it works. How it works: randomFunction returns a function which itself calls one of the arguments to randomFunction randomly.

This approach obviously only makes sense if you have several events, there you want a random function to respond to them. If it's only this single event, than using one of very versions above is simpler.

nikic