0

I would like for a callback function to fire after a click event. Currently I have the JavaScript

 $('#btnSubmit').click(function ()
            {
                $('#testDiv').hide('slow', onComplete('test'));
            });


            var onComplete = function (t)
            {
                $('#hiddenDiv').hide();
                alert(t);
            }

The callback function is supposed to be fired after the hiding of #testDiv. However, the onComplete function fires first. If I remove the parameters on onComplete and just give it a reference and not invoke it, then the function fires at the right time, but I can't pass parameters to it. How can I pass parameters to onComplete and not have it fire before the div is finished hiding?

fiddle here

1
  • try $('#testDiv').hide('slow', onComplete);, passing callback function reference rather than executing it. Commented Oct 6, 2013 at 18:38

3 Answers 3

2

You have to actually have a anonymous function there wrapping your onComplete():

$('#btnSubmit').click(function () {
    $('#testDiv').hide('slow', function () {
        onComplete('test')
    });
});

Demo here

In the jQUery docs:

complete
Type: Function()
A function to call once the animation is complete.

When adding onComplete() without a wrapping function the function will be called immediately, otherwise you need to reference it just with onComplete, but then you cannot pass your value unless you use .bind() to pass your parameter.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain why you have to have that anonymous function to call onComplete and you can't just call onComplete directly?
@wootscootinboogie Because you can't pass a function reference with attached parameters.
1

Use anonymous function:

$('#btnSubmit').click(function () {
   $('#testDiv').hide('slow', function () { 
      onComplete('test') 
   });
});

Comments

1

You can use .bind() :

$('#testDiv').hide('slow', onComplete.bind(null, 'test'));

The first parameter is the value this will have in the onComplete function. All other parameters are the argument list.

2 Comments

Why is the first parameter in bind null and not undefined?
@wootscootinboogie It doesn't matter what the first parameter is if you dont use this in the function onComplete.

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.