4

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"   />
rjmunro
  • 27,203
  • 20
  • 110
  • 132
JEagle
  • 147
  • 2
  • 2
  • 8
  • If you want toggle functionality get text and according to that call a particular function. – jaxb Jul 24 '10 at 10:58
  • possible duplicate of [How to use both onclick and ondblclick on an element?](http://stackoverflow.com/questions/1546040/how-to-use-both-onclick-and-ondblclick-on-an-element) – Gert Grenander Jul 24 '10 at 11:01
  • 1
    @Gert G: That is not related to the OP's question. – Felix Kling Jul 24 '10 at 11:02
  • Is that actually your code? Because that wouldn't produce a button in any web browser I've seen. Your HTML tag wouldn't have a name. Could you do View Source in your browser and show us the code from there? – Paul D. Waite Jul 24 '10 at 15:32

5 Answers5

5

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
  • 96,640
  • 56
  • 199
  • 270
  • If you're going to bother with an array, then maybe you should use `Math.round(Math.random() * functions.length)` – sje397 Jul 24 '10 at 12:12
  • @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 Jul 24 '10 at 13:18
3

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
  • 41,293
  • 8
  • 87
  • 103
2

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • hmm do you have an example i can explore? Edit:ok just saw it. Something with PHP? – JEagle Jul 24 '10 at 10:59
  • @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 Jul 24 '10 at 11:00
  • @ Jon Skeet. I have the 2 onclick working independently. My worry is how to add them to the same button. – JEagle Jul 24 '10 at 11:02
  • @JEagle: Read Jon's answer carefully: *Attach **one** event handler, and make **that single handler** **decide what to do randomly** .* – Felix Kling Jul 24 '10 at 11:04
  • I can't find a `C#` tag in this question anywhere. – jAndy Jul 24 '10 at 11:08
  • @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 Jul 24 '10 at 11:08
  • @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 Jul 24 '10 at 11:16
  • 2
    @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 Jul 24 '10 at 11:17
0
$('button').bind('click', function(){
    var rnd = Math.floor(Math.random() * 2);
    if(rnd)
       AnswerForEverthing();
    else
       WhatAmountOfWoodWouldAWouldchuckChuck();
});
jAndy
  • 231,737
  • 57
  • 305
  • 359
  • 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 Jul 24 '10 at 11:34
  • @Paul D. Waite: No, that behavior would happen if you multiply the result from `Math.random()` by `3`. – jAndy Jul 24 '10 at 11:48
  • @jAndy: Ah! Yes, sorry, Math.floor, gotcha. – Paul D. Waite Jul 24 '10 at 13:15
  • 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 Jul 24 '10 at 15:08
  • @jAndy, Ok it works. Now how can i make it work with this line: FREE . I tried to put there id="button" but it doesn't work... – JEagle Jul 24 '10 at 16:32
  • @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 Jul 24 '10 at 17:16
  • I had it already like: FREE but still no luck... What's going on? – JEagle Jul 24 '10 at 17:29
  • @JEagle: just add a `#` before the word `button` :) – jAndy Jul 24 '10 at 17:49
0
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
  • 100,734
  • 37
  • 191
  • 225