0

I have the following code with the purpose of making each .feedcontain div fade in after an increasing delay. The animation and formatting is perfect, its just that I can't have a this keyword in the first setTimeout() parameter.

function goFadeNow(){
    var loopdelay=250;
    $(".feedcontain").each(function() {
        setTimeout('$('+this+').addClass("appeared");',loopdelay);
        //$(this).addClass("appeared");
        loopdelay=loopdelay+250;
    });
}

If I uncomment line 5 and comment line 4, it works but it doesn't have the delay. PS: I do realize that I can't just use this like a normal variable.

Sabreok
  • 65
  • 1
  • 2
  • 6

2 Answers2

3

You can also bind() the function you are passing to this pointer:

function timeoutFunc() {
  $(this).addClass("appeared");
}

function goFadeNow(){
  var loopdelay=250;

  $(".feedcontain").each(function() {
    setTimeout(timeoutFunc.bind(this), loopdelay);
    loopdelay=loopdelay+250;
  });
}
Shalom Aleichem
  • 2,987
  • 2
  • 22
  • 34
  • What advantage do you think this offers over Matt's answer if any and why? – Benjamin Gruenbaum Jun 16 '13 at 05:12
  • 2
    Matt's solution saves the context of `goFadeNow` function, but the author of the question asked to pass the context of `each` function. The idea is the same, but we can operate with different meanings of `this` in the `timeoutFunc` just rebinding it do different contexts. – Shalom Aleichem Jun 16 '13 at 05:18
2
function goFadeNow(){
    var loopdelay=250;
    $(".feedcontain").each(function() {
        var $this = $(this);
        setTimeout(function () {
            $this.addClass("appeared");
        }, loopdelay);
        loopdelay=loopdelay+250;
    });
}
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • 2
    Why did you both answer and close vote? – Benjamin Gruenbaum Jun 16 '13 at 05:09
  • 1
    @BenjaminGruenbaum http://meta.stackexchange.com/questions/4283/closing-etiquette-why-do-some-answer-and-close/4288#4288 – Matt Ball Jun 16 '13 at 05:23
  • 2
    This solution is not quite right: you are always adding class `appeared` to the same `$this` element. But @ScorpionByte probably wanted to add this css class to each element returned by jQuery selector. To do that you should have saved `$(this)` inside function passed into `each` before calling `setTimeout`. – Shalom Aleichem Jun 16 '13 at 08:10
  • @AlexArgutin whoops, you're totally right! I shouldn't answer when tired. Sorry; fixed. – Matt Ball Jun 16 '13 at 16:20