Send simulated click arguments

How to send arguments when clicked?

// initiate the button $('#btn').click(function(e){ console.log(e.data); }); // later on I need to simulate a click with parameter $('#btn').click({ param : 'simulated click' }); 
+4
source share
3 answers

You can pass an additional parameter to the function handler using the trigger() method:

 // initiate the button $('#btn').click(function(e, data){ console.log(data); }); // later on I need to simulate a click with parameter $('#btn').trigger('click',{ param : 'simulated click' }); 

But if your goal is simply to check if the event was fired programmatically, you can check:

 // initiate the button $('#btn').click(function(e){ if(e.isTrigger) { console.log('simulated click'); } }); 
+1
source

Why can't we use .data() like this?

 $('#btn').click(function(e){ console.log($(this).data("param")); }); $('#btn').data("param",{param : 'simulated click'}).click(); 
+1
source

You can do this with $.trigger() , for example:

 $('#btn').click(function(e) { console.log(e.param); }); $('#btn').trigger({ type: "click", param: "simulated click" }); // => 'simulated click' 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="btn">Click me</button> 
0
source

All Articles