Skip to content Skip to sidebar Skip to footer

Accessing Variable Outside Of $(document).ready() & Jquery

so I have a .js file that is included into my html If I put this inside my .js file, $(document).ready(function(){ var siteRoot = $('.site-root').val(); alert(siteR

Solution 1:

You can either make it a global:

// this is the same as your example, // just wanted to stress that it's a part of the window (global) objectwindow.siteRoot = $('.site-root').val();
$(document).ready(function(){
      alert(window.siteRoot);
});

Or even better, use some kind of namespace, like this:

varMyData = {};
MyData.siteRoot = $('.site-root').val();

$(document).ready(function(){
  alert(MyData.siteRoot);
});

Solution 2:

The best way to do this is to basically create an empty global variable or create a namespace to store the variables. Then in the document.ready just add your $('.site-root').val() to that variable.

var siteRoot = '';

$(document).ready(function(){    
      siteRoot = $('.site-root').val();
      alert(siteRoot);
});

That way you set the siteRoot variable after you know .site-root exists and it is available globally throughout the application.

Solution 3:

The variable is available from within $(document).ready( since it is a global, but you are probably getting undefined because no value is available for .siteRoot before the document is ready. Just try this:

var siteRoot = "blahblah";
$(document).ready(function(){
      alert(siteRoot);
});

Now, if you expect a value to be available for that variable globally and for immediate use in other parts of your application, you will have to re-work your solution such that other parts of your application also make use of it only when the DOM is ready.

Solution 4:

Yet you can share by doing something like this:

$(document).ready(function(){
    window.siteroot = $('.site-root').val();
});

And throughout your app you could reference it via:

if (typeof(window.siteroot) !== "undefined") {
  //do this
}

You could also lazy load it:

window.get_siteRoot = function() {
   if (typeof(window.siteroot) !== "undefined")
      returnwindow.siteroot;

   var val = $('.site-root').val();
   window.siteroot = val;
   returnwindow.siteroot;
}

HTH.

Post a Comment for "Accessing Variable Outside Of $(document).ready() & Jquery"