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);
declare this
outside of
$(document).ready()
because,$(document).ready()
will hide your variable from global scope.Code
According to @Zakaria comment
Another way:
Note
outside of DOM ready function (currently you've) will log
undefined
, but within DOM ready it will give you true/ false.Your outer
console.log
execute before DOM ready execute, because DOM ready execute after all resource appeared to DOM i.e after DOM is prepared, so I think you'll always get absurd result.According to comment of @W0rldart
You can use following approach:
After change the value of
intro
I called a function that will fire with new value ofintro
.Use
window.intro
inside of$(document).ready()
.