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-pop
You need to use bind
or on
to add callbacks. In your case it should look like this:
var $input = $( ".ui-popup-container" ).find( "input" ).eq(2);
function runtests () {
console.log("clicked the input");
};
$input.bind('click', runtests);
Even shorter version for binding click is $input.click(runtests)
Then it will be called on click or you can trigger it manually with $input.trigger('click')
or simply $input.click()
.
When you call trigger
, the bound event handler is immediately executed, so you don't need any callback. Just use
$input.trigger('click');
runtests();
Trigger does not have callback function.
.trigger( eventType [, extraParameters ] )
Official Document
What you can do
var $input = $( ".ui-popup-container" ).find( "input" ).eq(2);
$input.on('click',function(){
console.log("clicked the input");
});
.trigger()
does not accept any callbacks. You don't need it most cases because the bound event handler is immediately executed. However, if you have an AJAX call in trigger event handler, the code from accepted answer will not work:
$input.trigger('click');
runtests();
You will have to use setTimeout()
like this:
$input.trigger('click');
setTimeout(function () {
runtests();
}, 250);
Or consider using success
or error
callbacks for .ajax()
call in .trigger()
event handler.
The Trigger doesn't have a callback function - you can better re-write your code to use the .on method.
$("body").on("click", "#click", function() {
alert("Clicked!");
});
JSFiddle.
If you have a click handler on every input but want to do something on a specific element:
var $container = $(".ui-popup-container"),
special = 2;
$container.on('click', 'input', function() {
// do something for every input
if($(this).index() == special) {
// your "callback", e.g. the function you want to execute on input:eq2 click
myfunction();
}
}).find('input').eq(special).trigger('click');