Reputation: 1819
I'm having trouble accessing a globally declared javascript variable that is declared in a separate file. My code:
<script src="scripts/one.js"></script>
<script src="scripts/two.js"></script>
One.js:
var config = {
form: 'form',
validate: {
'#first-name': {
'validation': 'required',
'error-msg': 'Required Field'
},
// other validation rules
}
};
Two.js:
$.validate({
modules: 'jsconf',
onModulesLoaded: function () {
$.setupValidation(config);
}
});
I receieve the error
Uncaught ReferenceError: config is not defined
on load of the page. Any reason why this would be happening when I am including the scripts in the appropriate order?
Upvotes: 0
Views: 155
Reputation: 6739
The problem is because the variable is defined in a function. Either move it outside of the function or use window.varName
var a = 1;
// File 1
$(function() {
var b = 2;
window.d = 4;
console.log(a);
});
// File 2
$(function() {
var c = 3;
console.log(a);
console.log(d);
console.log(b); // This will throw an error because b is not defined in this scope
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I suggest you read about JS scopes if you want to learn more.
Upvotes: 0
Reputation: 197
window.yourGlobalVariable
Use window.variable name to get variable between files.
Upvotes: 2