Search code examples
javascriptjqueryjquery-pluginsdelaysettimeout

Making delay() work with a plugin


I have a small plugin for setting the height of an element, based on several variable factors. On the page load, I wanted a delay in order to prevent the height from being set for a number of seconds. I know delay only works on effects, is there a way I can register my plugin as an effect, or do I need to do this another way?

Desire launch code:

$(".app_advert").delay(10000).set_height(2000);

Plugin Code:

       //SetHeight plugin
    (function($){
        $.fn.extend({
            set_height: function(time, callback){
                    scroll = $(window).scrollTop();

                    win_height = $(window).height();
                    document_height = $(document).height();


                    footer_height = $('#footer').height();
                    footer_offset = (document_height-(win_height+scroll));
                    footer_remainder = footer_height-footer_offset;

                return this.each(function(){
                    var x = $(this);

                    if(footer_height-footer_offset<=0){
                        height = 0;
                    } else {
                        height = footer_height-footer_offset;
                    }
                    $(x).stop(true, false).animate({bottom: height}, time, function(){
                        if (callback && typeof callback == 'function') { // make sure the callback is a function
                                callback.call(this); // brings the scope to the callback
                            }

                    });
                });
            }
        });

})(jQuery);

Solution

  • You would need to invoke jQuerys .queue() manually. Could look like;

    $(".app_advert").delay(10000).queue(function() {
        $(this).set_height(2000);
        $(this).dequeue();
    });
    

    You can even chain more queued methods on that construct behind. Beware, all fx methods are queued by default for any other method you want to apply to the current wrapped set, invoke another .queue().

    Have a read: http://api.jquery.com/queue