Passing jQuery to .animate callback

I installed a simple animator method:

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 would like to do is pass the jQuery string to run in the full callback. Everything else works fine. Like, for example, I would go to

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

in the callback?

Thanks!

+4
source share
2 answers

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

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

Then pass this function when you call Animator:

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

Or you can put the inline function:

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

Both work the same way, you can use any style depending on what makes your code more readable.

In any case, change your Animator code to:

  if( completeFunction ) { completeFunction(); }; 

Or you will often see what is written like this:

  completeFunction && completeFunction(); 

They both do the same. It's just a matter of taste that you are using, just thought that I mentioned both options so that you recognize them when you see them.

Note that the test !== null is not required here, and in fact this is not what you want. This is because if the caller does not pass into the completeFunction , the value of this variable will be undefined , not null , so your test will not work. Interestingly, in this case, you can use != null , because it will be checked for both null and undefined and treat them the same way. But actually you just don't need this explicit test at all, if the only thing you check is whether the calling code provided the callback to completeFunction or not.

+4
source

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); }) 
0
source

All Articles