How to run a callback function on a jQuery trigger("click")?

frequent picture frequent · Mar 20, 2013 · Viewed 83.1k times · Source

I need to trigger a custom event in the callback of a trigger call, but I can't get it to work.

I tried this:

var $input = $( ".ui-popup-container" ).find( "input" ).eq(2);

function runtests () {
    console.log("clicked the input");
};
$input.trigger('click', runtests()); 

and this:

var $input = $( ".ui-popup-container" ).find( "input" ).eq(2);
$input.trigger('click', function(){
    console.log("clicked the input");
}

Neither of which works.

Question:
How do I get a callback function to run when I'm triggering a click on an element?

Answer

Denys Séguret picture Denys Séguret · Mar 20, 2013

When you call trigger, the bound event handler is immediately executed, so you don't need any callback. Just use

$input.trigger('click');
runtests();