fcalderan
fcalderan

Reputation:

Jquery callback with synchronous animations

In my jQuery plugins I often expect to have some callbacks defined by the user like in the simple example below

(function($) {
    $.fn.myplugin = function(options) {
        var s = $.extend({}, options),
            $this = $(this);

        if (typeof s['initCallback'] === 'function') {
            s['initCallback']($this);    
        }
        $this.animate({width: '+=300'}, 3000);   /* animation in plugin */
    }
})(jQuery);

Sometimes the defined callback contains synchronous code like this, and this code works as I'm expecting

$('#mydiv').myplugin({
    initCallback : function(mydiv) {
       $('<div>This is synchronous, so it will entirely executed before animation</div>')
           .insertBefore(mydiv);
    }   
});

but in some other case the callback could defines an asynchronous animation like this

$('#mydiv').myplugin({
    initCallback : function(mydiv) {
       $('<div>animations are not synchronous here</div>')
           .insertBefore(mydiv)
           .hide()
           .fadeIn(4000); /* animation in callback */
    }   
});

in this last case we have two animations that clearly overlap, because after execution of my initCallback() the remaining plugin code is not properly executed on fadeIn() callback.

So I'm asking: does it exists a common jQuery pattern to deal with both kind of code (async/sync) to be sure that the initCallback() will ever terminate the execution, no matter of which code it defines? Or am I require to code both the case in two different ways?

Code of this example is available on http://jsfiddle.net/fcalderan/LKttT/

Thanks in advance.

Upvotes: 0

Views: 867

Answers (1)

jantimon
jantimon

Reputation: 38150

http://api.jquery.com/animate/

.animate( properties, options )

propertiesA map of CSS properties that the animation will move toward.

optionsA map of additional options to pass to the method. Supported keys:

  • duration: A string or number determining how long the animation will run.
  • easing: A string indicating which easing function to use for the transition.
  • complete: A function to call once the animation is complete.
  • step: A function to be called after each step of the animation.
  • queue: A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately.
  • specialEasing: A map of one or more of the CSS properties defined by the properties argument and their corresponding easing functions (added 1.4).

You should set queue to false.

Upvotes: 1

Related Questions