Reputation: 125
var $target = $("#a");
$(document).ready(function() {
$target.fadeOut('fast');
});
a is a list item. For some reason, it wont fade out when the variable is defined outside of $(document).ready(). I thought that if I defined $target in the global scope, I can access it inside a function.
Can you tell me the difference between defining it outside and inside the document.ready function?
Upvotes: 0
Views: 70
Reputation: 18873
The problem in your case is that outside $(document).ready(function(){})
the DOM is not completely loaded and when you are assigning var $target = $("#a");
(outside $(document).ready(function(){})
) then may be no $("#a")
(element with id
'a') inside DOM.The $(document).ready(function(){})
event fires when your html (DOM) is completely loaded.
Proper jquery code should look like :
$(document).ready(function() {
var $target = $("#a");
$target.fadeOut('fast');
});
Upvotes: 0
Reputation: 251
When you are setting the $target variable, the document is not loaded yet, you need to do that into "ready" function.
Try this 3 posibilities:
//with global variable.
var $target = false;
$(document).ready(function() {
$target = $("#a");
$target.fadeOut('fast');
});
//with local variable.
$(document).ready(function() {
var $target = $("#a");
$target.fadeOut('fast');
});
//without variable
$(document).ready(function() {
$("#a").fadeOut('fast');
});
Upvotes: 1