As you saw, it thishas a different meaning inside setTimeout().
One solution is to store the correct value thisin the variable and reference it in the anonymous function that you pass.
$(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 $.proxy(), which will keep the value for you this.
$(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 can 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 );
});
});
source
share