Aaron
Aaron

Reputation: 2500

Pass jQuery to .animate Callback

I've setup a simple animator method like so:

Animator: function (obj, aniArgs, duration, aniEasArgs, completeFunction) {
    obj.stop(true, true).animate(aniArgs, {
        duration: duration,
        queue: false,
        specialEasing: aniEasArgs,
        complete: function () {
            if (completeFunction !== null) {

            };
        }
    });
    return obj;
},

What I'd like to do is be able to pass in string of jQuery to run in the complete callback. Everything else works fine. How, for example, would I pass in

$('#someElement').hide(500);

into the callback?

Thanks!

Upvotes: 4

Views: 170

Answers (2)

Michael Geary
Michael Geary

Reputation: 28850

First, create a function with the code you want to run:

function complete() {
    $('#someElement').hide(500);
}

Then, pass that function in when you call Animator:

Animator( obj, aniArgs, duration, aniEasArgs, complete );

Or, you can put the function inline:

Animator( obj, aniArgs, duration, aniEasArgs, function() {
    $('#someElement').hide(500);
});

Those both work the same way, you can use either style depending on what makes your code easier to read.

Either way, change your Animator code to:

        if( completeFunction ) {
            completeFunction();
        };

Or, you'll often see that written this way:

        completeFunction && completeFunction();

They both do exactly the same thing. It's just a matter of taste which you use, just thought I'd mention both variations so you'll recognize them when you see them.

Note that the !== null test is not required here, and in fact isn't what you want. That's because if the caller does not pass in a completeFunction, the value of that variable will be undefined, not null, so your test won't work. Interestingly enough, you can use != null in this case, because that will test for both null and undefined and treat them the same. But really you just don't need this explicit test at all, if the only thing you're checking for is whether the caller provided a completeFunction callback or not.

Upvotes: 4

Arun P Johny
Arun P Johny

Reputation: 388316

Try

Animator: function (obj, aniArgs, duration, aniEasArgs, completeFunction) {
    obj.stop(true, true).animate(aniArgs, {
        duration: duration,
        queue: false,
        specialEasing: aniEasArgs,
        complete: function () {
            if (jQuery.isFunction(completeFunction )) {
                completeFunction.apply(this, arguments);
            };
        }
    });
    return obj;
},

Theb

x.Animator(obj, aniArgs, duration, aniEasArgs, function(){
    $('#someElement').hide(500);
})

Upvotes: 0

Related Questions