tags:

views:

42

answers:

3

Hi folks. I am trying to write a function where I need to reference "this" inside of window.setTimeout. Currently it doesn't work. How can I rewrite this so it works? Thanks.

 $(function() {
     $('li a').click(function() {
          $(this).parent().css('background-position','left top');
          window.setTimeout("$(this).css('font-size','40px');",1000);
     });
 });
+4  A: 

As you saw, this has a different meaning inside a setTimeout().

One solution is to store the correct value of this in a variable, and reference it in the anonymous function that you pass in.

 $(function() {
     $('li a').click(function() {
          $(this).parent().css('background-position','left top');
          var th = this;
          window.setTimeout(function() {
                     $(th).css('font-size','40px');
                },1000);
     });
 });

Another option is to use jQuery's $.proxy() which retains the value of this for you.

 $(function() {
     $('li a').click(function() {
          $(this).parent().css('background-position','left top');
          window.setTimeout($.proxy(function() {
                     $(this).css('font-size','40px');
                }, this)
          ,1000);
     });
 });

Otherwise, you could create a closure.

 $(function() {
     $('li a').click(function() {
          (function( th ) {
              $(th).parent().css('background-position','left top');
              window.setTimeout(function() {
                         $(th).css('font-size','40px');
                    }
              ,1000);
          })( this );
     });
 });
patrick dw
@Kranu - `$.proxy` takes care of that. Otherwise a closure.
patrick dw
Oh I never actually new about proxy. +1 to your answer for having multiple methods.
Kranu
@Kranu - Thanks. I personally prefer the closure, just feels lighter, but `$.proxy()` certainly does the trick.
patrick dw
A: 

You need to create a closure inside your setTimeout call.

 $(function() {
      $('li a').click(function() {
            var $this = $(this);
            $this.parent().css('background-position','left top');
            window.setTimeout(function () {
                $this.css('font-size','40px');
            },1000);
          });
     });

Should be much closer.

g.d.d.c
The anonymous function is good, but `setTimeout()` still calls the function from a different context, so `this` will have a different meaning.
patrick dw
I believe you're right. Adjusted to reflect.
g.d.d.c
A: 
     window.setTimeout(function(){$(this).css('font-size','40px')},1000);

No quotes. And it needs to be a function.

Chris
Won't quite work. See my or @g.d.d.c.'s answer. :o)
patrick dw