Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global javascript variable inside document.ready

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); 
like image 532
Alex Avatar asked Jun 22 '12 08:06

Alex


People also ask

Can we declare global variable in JavaScript?

Declaring Variable: A variable can be either declared as a global or local variable. Variables can be declared by var, let, and const keywords. Before ES6 there is only a var keyword available to declare a JavaScript variable.

What is difference between $( function () and document Ready?

So technically they are both the same. Not major difference between these two declaration. They used based on weather you use JavaScript then you should use $(document). ready declaration in other case you use jQuery library which is a part of JavaScript then you should use $(function) declaration.

Where are global variables stored in JavaScript?

Are global variables stored in specific object? The answer is yes; they are stored in something called, officially, the global object. This object is described in Section 15.1 of the official ECMAScript 5 Specification.

Can we write function inside document ready?

Yes, you can do that, it's just a matter of scope. If you only need to access callMe() from within $(document). ready(function() { }) , then it's fine to put the function there, and offers some architecture benefits because you can't access the function outside of that context.


1 Answers

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" 
like image 105
McGarnagle Avatar answered Sep 22 '22 15:09

McGarnagle