I have this jQuery code:
$('#loadingDiv2')
.css('visibility','hidden') // hide it initially
.ajaxStart(function() {
$(this).css('visibility','visible');
$("#bbdata").empty();
})
.ajaxStop(function() {
$(this).css('visibility','hidden');// works here
setTimeout(function(){
$(this).css('visibility','hidden');// doesn't work here
}, 100);
});
why $(this) doesn’t work in a setTimeout method?
It doesn’t work because
thisis a different context at that point (window), you have a few optons though, store a reference to what you want to deal with, like this:Or use
$.proxy()for to set the context in that anonymous function, like this:In the first solution we store a reference to what we want to deal with, in the second we’re actually setting that
thisis when that function runs…otherwise it’ll bewindow.