Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using $(this) in setTimeout();

I want to set timeouts dynamically in jQuery. The dynamically set timeout functions need to use $("this"), but I can't seem to get it working.

An exmple:

$("div").each(function(){
    var content = $(this).attr('data-content')
    setTimeout("$(this).html('"+content+"')",$(this).attr('data-delay'));
});​

http://jsfiddle.net/qmhmQ/

What is the best way to do this?

like image 221
ONOZ Avatar asked May 09 '12 08:05

ONOZ


2 Answers

$("div").each(function(){
    var content = $(this).attr('data-content'),
        $this = $(this); // here $this keeps the reference of $(this)
    setTimeout(function() {

      // within this funciton you can't get the $(this) because
      // $(this) resides within in the scope of .each() function i.e $(this)
      // is an asset of .each() not setTimeout()
      // so to get $(this) here, we store it within a variable (here: $this) 
      // and then using it

        $this.html(content);
    }, $this.attr('data-delay'));
});​

DEMO

like image 63
thecodeparadox Avatar answered Sep 27 '22 02:09

thecodeparadox


Your code should look like this:

  1. pass a function instead of a string. Explanation: When passing a string to setTimeout you get problems, because it runs in a different scope than you original one, and thus you get errors.

  2. use the jQuery data()method

    $("div").each(function(){
         var content = $(this).attr('data-content'),
             $el = $(this),
             setContent = function(){
                $el.html(content);
             }
         setTimeout(setContent,$el.data('delay'));
    });​
    

You can assign a function to a variable and pass that variable as parameter to setTimeout, this is the cleanest way.

like image 21
Christoph Avatar answered Sep 26 '22 02:09

Christoph