Search code examples
javascriptjquerycssdelayslidedown

How to use delay() with each()?


$("#home #oneTool").prepend($(".userInfo.module"));

var topVal = $(".userInfo.module").height();
$(".userInfo.module").hide();
$(".userInfo.module").slideDown(3000);

$("#home #oneTool div.divspot").each(function(){
   var newVal = topVal + parseInt($(this).css('top'));
   $(this).css('top',newVal);
});

The .userInfo.module is present above all div.divspots...

Since i'm using slideDown, the each function needs to be delayed, so that the div.divspots could also slidedown smoothly.. (will delay be helpful?)

Note: All div.divspots are absolutely positioned


Solution

  • Well first of all, slideDown takes as a parameter a function to call after it's done. http://api.jquery.com/slideDown/

    Props to another answerer who realized what you were asking and a #fail to me for not reading your question properly.

    That being said, for a method that does not have a callback after completion, here are a couple of options.

    Two options:

    1. Use queue
    2. Use setTimeout

    Use queue:

    http://api.jquery.com/queue/

    $(".userInfo.module").fooThatTakes(3000).queue(function() {
      $("#home #oneTool div.divspot").each(function(){
        var newVal = topVal + parseInt($(this).css('top'));
        $(this).css('top',newVal);
      });
    });
    

    Use setTimeout.

    var delay = 3000;
    $(".userInfo.module").fooThatTakes(delay);
    t = setTimeout(afterFoo, delay);
    
    function afterFoo() {
      $("#home #oneTool div.divspot").each(function(){
        var newVal = topVal + parseInt($(this).css('top'));
        $(this).css('top',newVal);
      });
    }