Global javascript variable inside document.ready

105,783

Solution 1

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...

var MyProject = {};
$(document).ready(function() {
    MyProject.intro = "";

    MyProject.intro = "something";
});

console.log(MyProject.intro); // "something"

Solution 2

declare this

var intro;

outside of $(document).ready() because, $(document).ready() will hide your variable from global scope.

Code

var intro;

$(document).ready(function() {
    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>');
            }
        }
    });
});

According to @Zakaria comment

Another way:

window.intro = undefined;

$(document).ready(function() {
    if ($('.intro_check').is(':checked')) {
        window.intro = true;
        $('.intro').wrap('<div class="disabled"></div>');
    };
    $('.intro_check').change(function(){
        if(this.checked) {
            window.intro = false;
            $('.enabled').removeClass('enabled').addClass('disabled');
        } else {
            window.intro = true;
            if($('.intro').exists()) {
                $('.disabled').removeClass('disabled').addClass('enabled'); 
            } else {
                $('.intro').wrap('<div class="disabled"></div>');
            }
        }
    });
});

Note

console.log(intro);

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

I need to use it outside of DOM ready function

You can use following approach:

var intro = undefined;

$(document).ready(function() {
    if ($('.intro_check').is(':checked')) {
        intro = true;
        introCheck();
        $('.intro').wrap('<div class="disabled"></div>');
    };
    $('.intro_check').change(function() {
        if (this.checked) {
            intro = true;
        } else {
            intro = false;
        }
        introCheck();
    });

});

function introCheck() {
    console.log(intro);
}

After change the value of intro I called a function that will fire with new value of intro.

Solution 3

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.

$(document).ready(function() {
   intro = null; // it is in global scope now

To learn more about it, check out:

Solution 4

Use window.intro inside of $(document).ready().

Solution 5

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

$(document).ready(function() {
    intro =  "something";
});

although you cant use the variable immediately, but it would be accessible to other functions

Share:
105,783
Alex
Author by

Alex

Why stop learning?

Updated on July 09, 2022

Comments

  • Alex
    Alex almost 2 years

    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);
    
  • Zakaria
    Zakaria almost 12 years
    If my understanding is correct, the question is about declaring a global var inside the $(document).ready() function.
  • Admin
    Admin almost 12 years
    Not what the OP asked for, but cleaner. I'd prefer a closure, though, unless the code is modular, and there's a requirement for cross-module access to the global variable.
  • Alex
    Alex almost 12 years
    @Zakaria I don't care where the variale is declared, I just need it to be global so I can access it from everywhere
  • Esailija
    Esailija almost 12 years
    @OliverWeiler global variables per say aren't but being explicit about when you're modifying a global variable is pretty good practice I'd say...
  • Alex
    Alex almost 12 years
    For some reason, it won't go! When I try the alert(intro) or console.log(intro) it keeps returning undefined. I tried almost all the solutions proposed in this thread
  • thecodeparadox
    thecodeparadox almost 12 years
    @w0rldart you console.log outside of DOM ready function (currently you've) will log undefined, but within DOM ready it will give you true/ false.
  • Sarfraz
    Sarfraz almost 12 years
    @w0rldart: There should be something else wrong. Make sure that you are not re-defining that variable somewhere else and also beware of javascript hoisting: adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting. And try your console.log command inside the ready handler which is where you manipulate the intro variable.
  • Alex
    Alex almost 12 years
    @thecodeparadox I need to use it outside of DOM ready function, because I will use later on in tinymce to know what to activate or not
  • thecodeparadox
    thecodeparadox almost 12 years
    @w0rldart 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.
  • thecodeparadox
    thecodeparadox almost 12 years
    @w0rldart I have update my answer, I think my last part will work for you
  • Alex
    Alex almost 12 years
    @dbaseman, I like your solution because it would solve some problems and improve some of my code (the code It was prebuild, I just improve it)... but for some reason, when I declare MyProject.intro = "something"; inside DOM Ready function, I keep getting undefined as output in console.log
  • d.raev
    d.raev about 10 years
    @w0rldart In the OP code and in the accepted answer, the console log is outside the $(document.ready(...)). So in most of the cases the the console.log will run when the JS is loaded, and AFTER THAT the Ready function will be executed when all the DOM is ready.
  • ming
    ming over 5 years
    Thanks! But why is that I can't console.log() the global variable when I declare it inside $(document).ready ?
  • Hayden Thring
    Hayden Thring almost 5 years
    Lovely ! So simple