Navin Rauniyar
Navin Rauniyar

Reputation: 10525

addClass not working within setTimeout function

demo

$('button').on('click',function(){
   setTimeout(function(){
      $(this).addClass('active');
   },500);
});

The active class should be added after 500 ms but it's not adding that is not changing it's background color.

Upvotes: 4

Views: 11837

Answers (4)

Arun P Johny
Arun P Johny

Reputation: 388316

this doesn't refer to the clicked button inside the setTimeout() handler, you can use a simple closure variable to hold a reference to the clicked element and use it in the timeout handler

$('button').on('click', function () {
    var $el = $(this);
    setTimeout(function () {
        $el.addClass('active');
    }, 500);
});

Upvotes: 9

Milind Anantwar
Milind Anantwar

Reputation: 82231

Try this:

$('button').on('click',function(){
 var that = $(this);
 setTimeout(function(){that.addClass('active');},500);
});

Working Fiddle

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

use proxy:

$('button').on('click',function(){
   setTimeout($.proxy(function(){
      $(this).addClass('active');
   },this),500);
});

within setTimeout function 'this' refers to window object not to the button that you click on but using proxy the 'this' defines the button that you click on.

demo

Upvotes: 3

Felix
Felix

Reputation: 38102

You can save $(this) in a variable in order to access $(this) in your setTimeout function:

$('button').on('click',function(){
    var $this = $(this);
    setTimeout(function(){
        $this.addClass('active');
    },500);
});

Updated Fiddle

Upvotes: 1

Related Questions