Reputation: 10525
$('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
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
Reputation: 82231
Try this:
$('button').on('click',function(){
var that = $(this);
setTimeout(function(){that.addClass('active');},500);
});
Upvotes: 0
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.
Upvotes: 3
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);
});
Upvotes: 1