Unable to access javascript variable from another file - javascript

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?

window.yourGlobalVariable
Use window.variable name to get variable between files.

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.

Related

How to send a variable inside of a function to be accessed in another file in Nodejs

I have 2 files named test.js and test2.js , I write a function in test1.js which stores a value in a variable from the function call, but I am unable to access that value in the variable in test2.js file.
If you declare the variable in a global scope first in the initial script and assign it (without redeclaring) you can achieve this pretty simply. Perhaps show your code so can see a bit better what your issue is?
//test1.js
let test = 'test';
function changeTest(change = null) {
test = change || test;
}
//test2.js
(() => {
console.log(`GLOBAL VARIABLE: ${test}`); // test is 'test'
changeTest('changed');
console.log(`AFTER CHANGE: ${test}`); // test is 'changed'
})();
See https://www.w3schools.com/js/js_scope.asp for more information on JS scope management
So it is technically feasible but maybe not recommended.
# file 1
let test1 = 0;
function init1 {test1 = 2;};
init1();
export function getTest1() {return test1};
# file 2
import { getTest1 } from './file1';
function logTest1() {
console.log(getTest1());
}

Pass variable from one Javascript File to the another ( specific situation )

I have 2 different Javascript files.
How to i pass a Javascript variable inside a Jquery document function to another Javascript file.
chat.js
$(document).ready(function () {
var a = "something"
}
to scripts.js
$(document).ready(function () {
console.log(a); //gives undefined
}
index.html
<script type="text/javascript" src="/js/chat.js"></script>
<script type="text/javascript" src="/js/scripts.js"></script>
Notes: i am aware this theres a duplicate but not of this specific situation
I have tried multiple solutions such as globally declare the variable but wont work for me since this is for a socket.
Maybe you can use localStorage?
Try this:
Chat.js
$(document).ready(function () {
var a = "something";
localStorage.setItem('a', a);
}
Scripts.js
$(document).ready(function () {
console.log(localStorage.getItem('a'));
}
In chats.js:
var a;
$(document).ready(function () {
a = "something"
}
In scripts.js:
$(document).ready(function () {
console.log(a); //gives something
}
Either make a global(window) level variable and use it on both js file,
or make global level function and pass the local variable as parameter to global function.

Pass a value and print it in javascript

I'm trying to pass a lang variable in my js files.
Actually I have this:
<script src="assets/js/plugins.js?lang=en"></script>
In plugins.js, I have this:
var LIBS = {
// Chart libraries
validation: [
"assets/libs/validation/jquery.validation.min.js",
"assets/libs/validation/lang/xxxxxx.min.js"
],
...
};
How can I get the lang value passed to replace my xxxxxx by the lang en ?
Thanks.
try this in your plugin.js
var LIBS = {
// Chart libraries
validation: [
"assets/libs/validation/jquery.validation.min.js",
"assets/libs/validation/lang/xxxxxx.min.js"
]
};
LIBS.tmpValidation = LIBS.validation;
LIBS.validation = [];
LIBS.lang = "en";
Object.defineProperty(LIBS, "validation", {
get : function(){
var self = this;
return this.tmpValidation.map(function(item){
return item.replace(/xxxxxx/g, self.lang)
})
}
});
console.log(LIBS.validation);
You can now define your plugin in such a way that lang property is set to LIBS before invoking LIBS.validation
You can use a global variable.
Global variable:
I've used an object here to store settings, you could add more settings, if you wish
var settings = { lang:'en' };
Your other script (plugins.js):
var LIBS = {
// Chart libraries
validation: [
'assets/libs/validation/jquery.validation.min.js',
'assets/libs/validation/lang/' + settings.lang + '.min.js'
],
...
};
Here's a full example script that does precisely what I'm talking about above. I've got LIBS declared in the same script, but it could just as easily be included in plugins.js and declared below the setting of the global settings variable in this script instead...
Example Script:
<script>
var settings = { lang:'en' };
console.log(settings); // Show that the value has been set.
var LIBS = {
// Chart libraries
validation: [
'assets/libs/validation/jquery.validation.min.js',
'assets/libs/validation/lang/' + settings.lang + '.min.js'
]
};
// Show that LIBS has been set with the language setting from the global variable.
console.log(LIBS);
</script>
After you've run this, then you will see that the variable has been picked up and the second entry in the array is assets/libs/validation/lang/en.min.js
Or to be closer to your own example...
<script>
var settings = { lang:'en' };
console.log(settings); // Show that the value has been set.
</script>
<!-- Following line must come after the script above
this JS file can now access that global settings variable -->
<script src="plugins.js"></script>
try
var s = document.getElementsByTagName('script'),
ss = s[s.length-1];
lang = ss.src.match(/\?lang=(\w\w)/);
// sure... check it exists!
console.debug(lang[1]);
inside plugins.js

Execute global javascript code anonymously

I have the following html:
<script type="text/javascript" src="before.js"></script>
<script type="text/javascript" src="globalCode.js"></script>
<script type="text/javascript" src="after.js"></script>
The globalCode.js file contains:
function doStuff() {
return 1 + 2;
}
module.export = doStuff();
I want to get the contents of module.export but without letting doStuff() get into the global context.
So basically I would like the following functionality:
var module = {};
(function() {
function doStuff() {
return 1 + 2;
}
module.export = doStuff();
}();
with the restriction that I can not modify globalCode.js and can only use before.js & after.js.
I thought about saving the global object in before.js and restoring it in after.js but I am not quite sure how.

Access variable from another script source

<script src="http://domain.com/source1.js"></script>
<script src="http://domain.com/source2.js"></script>
source1.js
var PICTURE_PATH = "";
var PICTURE_ROOT = base_url+"YOUTAILOR_files/";
var PROGRAM = parseInt("1");
source2.js
if(PROGRAM==3 || PROGRAM==4 || PROGRAM==5)
{
}
I could not access value of program in source2.js..
When you declare var source1Var outside a function you are actually creating a variable on the window object. So you should just be able to access it from source2.js. Just make sure source1.js is before source2.js in the script tags...
If however you're declaring it within a function, it will be private to that function. If you really need to you could set it on window explicitly.
In source1.js
function foo() {
window.source1Var = 3;
}
In source2.js
function bar() {
console.log(source1Var); // this will search window if it cannot find in the local scope.
}
What is the problem you're trying to solve? It is generally better to use some form of dependency injection, event listeners, builder pattern etc. rather than using global variables.
do something like in your first .js
var VAR = {
myvalue: "hai"
};
then call it in second like
alert(VAR.myvalue);
It's easier than you think. If variable is global, you should access it from anywhere.
// source1.js
var colorCodes = {
back : "#fff",
front : "#888",
side : "#369"
};
And in another file:
// source2.js
alert (colorCodes.back); // alerts `#fff`

Categories