kamikaze_pilot
kamikaze_pilot

Reputation: 14834

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(siteRoot);
});

the code would alert the value properly, but if I do this:

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

it would alert undefined instead

is there a way to have something that's in $(document).ready() access variables outside it since if I put the variable inside $(document).ready() it wouldn't be accessible from other js files

Upvotes: 14

Views: 24065

Answers (4)

karim79
karim79

Reputation: 342655

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.

Upvotes: 2

Dave Long
Dave Long

Reputation: 9759

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.

Upvotes: 2

Brian Mains
Brian Mains

Reputation: 50728

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")
      return window.siteroot;

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

HTH.

Upvotes: 0

Pablo Fernandez
Pablo Fernandez

Reputation: 105220

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) object
window.siteRoot = $('.site-root').val();
$(document).ready(function(){
      alert(window.siteRoot);
});

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

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

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

Upvotes: 23

Related Questions