Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"   />
like image 789
JEagle Avatar asked Dec 28 '22 09:12

JEagle


1 Answers

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]();
    }
);
like image 118
Paul D. Waite Avatar answered Dec 30 '22 23:12

Paul D. Waite