34

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?

10
  • 1
    Why are you adding undefined as second parameter to trigger ? What's that second parameter supposed to do ? Are you confusing trigger and bind ? Commented Mar 20, 2013 at 9:16
  • That's my attempt at a callback function... I also tried wrapping it in [] as per jquery API, but also does not work Commented Mar 20, 2013 at 9:17
  • 1
    .trigger does not accept any callbacks. $input.trigger('click') triggers the click event on the $input elements, i.e. it will execute the click event handlers bound to those elements. It looks like you have bind runtest to $input, but I'm not sure what your want exactly. Commented Mar 20, 2013 at 9:17
  • But how is this callback supposed to be used ? Commented Mar 20, 2013 at 9:17
  • @FelixKling: I need to click the input and after it has executed it's own handlers, I need to run a set of qunit tests (to check whether the input did what it should) Commented Mar 20, 2013 at 9:18

10 Answers 10

29

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

$input.trigger('click');
runtests();
Sign up to request clarification or add additional context in comments.

4 Comments

+1 That should work fine, according to the docs: qunitjs.com/cookbook/#testing-user-actions.
@frequent, you were getting callbacks and handlers confused, of course. If there's no asynchronous activity associated with the action, it's a handler that you trigger, whereas if there is asynchronous activity, you assign a callback to handle it's response when it occurs (or by status).
This does not work for me. I get a race condition unless I use setTimeout on the runtests() function in the example.
this doesn't work when you have a long js code in the second part of the code and at end an ajax call. only solution which is a ugly one but settimeout seems to work
29

Yes - It is true that trigger doesn't take callback but we can pass callback as parameter.

//.trigger( eventType [, extraParameters ] )

$("#element").bind("customCall", function(e, callback){
   callback();
}
var callback = function(){alert("Hello");}
$("#element").trigger("customCall",[callback]);

Hope this will helps

3 Comments

If you're already familiar with the convention for assigning callback functions when defining a bound event for a DOM element, this answer actually tells you how you could actually pass a dynamic callback function at the time that the event is triggered. That makes it one of the most valuable answers on this page, to me.
Agree with @tobylaroni. Not sure why this was not the accepted answer! Probably the question was specific to 'trigger' than a custom call.
12

First you need to bind the click event and then you can trigger the click event.

$input.bind('click', function() {

     console.log("clicked the input");
});

$input.trigger('click');

3 Comments

yup. thats one way. Thanks.
Use .on() instead of .bind().
Question is about $input.trigger('click', function(){//code when the click function has been completed});
5

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");
});

Comments

2

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().

Comments

0

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.

Comments

0

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');

Comments

0

.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.

Comments

0

Denys Séguret's logic is right. But when needed a callback function after trigger function, $.when is usable:

$.when($input.trigger("click"))
 .done(function () { runtests(); });

Comments

0

Please try this :

$('#inputTxt1').change(function(e, callback1, data) {

    /*  other statement ...   */  
    
   if(typeof(callback1)==='function'){
       callback1(data);
   } 
});

$('#button2').click(function(e){
    $('#button1').trigger('change', [secondCallback, 'data to callback']);
});

function secondCallback(data){
    var result = data;
} 

2 Comments

Could you provide more details on what the code does and how it helps the OP?
Oops! I misunderstand about question. Actually I just really want to show some nested triggering. Hope this is the gift for someone who are looking for this solution. Im very sorry and thanks for your remind.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.