How to fire a function before and after automatically in a jquery plugin?

How should I implement beforeAnimate and afterAnimate callbacks in the following jQuery plugin?

  • Let's assume this is my plugin: // writing the plugin (function($){ $.fn.myPlugIn = function(options){ defaults = { beforeAnimate : function(){}, afterAnimate : function(){} } options = $.extend(defaults, options); //here is where I need help options.beforeAnimate(); $(this).animate({'width':'1000px'},1000); options.afterAnimate(); } })(jQuery); //using the plugin $('#art2').myPlugIn({ beforeAnimate: function(){ $('#art1').animate({'width':'1000px'},1000); }, afterAnimate: function(){ $('#art3').animate({'width':'1000px'},1000); } }); How should I rewrite this part: options.beforeAnimate(); $(this).animate({'width':'1000px'},1000); options.afterAnimate(); In order to get the 3 animate calls one after other. (i.e waiting for the previous one has finished)

  • Answer:

    $(this).animate({'width':'1000px'}, 1000, {complete:options.afterAnimate});

Evan Q Jones at Quora Visit the source

Was this solution helpful to you?

Other answers

Update your beforeAnimate to provide a callback: $('#art2').myPlugIn({ beforeAnimate: function(callback){ $('#art1').animate({'width':'1000px'},1000,callback); }, afterAnimate: function(){ $('#art3').animate({'width':'1000px'},1000); } }); Then you may queue them up like this: options.beforeAnimate(function(){ $(this).animate({'width':'1000px'},1000, options.afterAnimate() ); }); This should work but will only get ugly! You may also want to give a look at jquery.deferred http://api.jquery.com/category/deferred-object/

Prashant Chaudhary

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.