Which is the right way of declaring a global javascript variable? The way I'm trying it, doesn't work
$(document).ready(function() {
var intro;
if ($('.intro_check').is(':checked')) {
intro = true;
$('.intro').wrap('<div class="disabled"></div>');
};
$('.intro_check').change(function(){
if(this.checked) {
intro = false;
$('.enabled').removeClass('enabled').addClass('disabled');
} else {
intro = true;
if($('.intro').exists()) {
$('.disabled').removeClass('disabled').addClass('enabled');
} else {
$('.intro').wrap('<div class="disabled"></div>');
}
}
});
});
console.log(intro);
JavaScript has Function-Level variable scope which means you will have to declare your variable outside
$(document).ready()
function.Or alternatively to make your variable to have global scope, simply dont use
var
keyword before it like shown below. However generally this is considered bad practice because it pollutes the global scope but it is up to you to decide.To learn more about it, check out:
Unlike another programming languages, any variable declared outside any function automatically becomes global,
You problem is that you declare variable inside
ready()
function, which means that it becomes visible (in scope) ONLY insideready()
function, but not outside,Solution: So just make it global, i.e declare this one outside
$(document).ready(function(){});
Use
window.intro = "value";
inside the ready function."value"
could bevoid 0
if you want it to beundefined
like this: put
intro
outside your document ready, Good discussion here: http://forum.jquery.com/topic/how-do-i-declare-a-global-variable-in-jquery @thecodeparadox is awesomely fast :P anyways!You can define the variable inside the document ready function without var to make it a global variable. In javascript any variable declared without var automatically becomes a global variable
although you cant use the variable immediately, but it would be accessible to other functions
If you're declaring a global variable, you might want to use a namespace of some kind. Just declare the namespace outside, then you can throw whatever you want into it. Like this...