0

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?

7
  • 1
    are your paths to the files correct? Commented Apr 6, 2017 at 13:41
  • 1
    Are you sure it is actually loading? Network tab? Commented Apr 6, 2017 at 13:41
  • look under network in the console Commented Apr 6, 2017 at 13:41
  • Is the whole of the files? Or are they wrapped in an IIFE? Commented Apr 6, 2017 at 13:41
  • 1
    @noclist if they're wrapped in the Jquery ready function, then they're only accessible to/in that function. Look at JS scopes Commented Apr 6, 2017 at 13:46

2 Answers 2

2
window.yourGlobalVariable

Use window.variable name to get variable between files.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.