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

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.

Related

Unable to access javascript variable from another file

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.

Call function from another js file when using iife pattern?

Is it possible to call function that is in one js file and it is made public by usage of iife pattern, in another js file?
For example, this is some validationScript.js file:
var ValidationNamespace = function ()
{
var nameValidation = "";
var testValidation = "";
return{
validateIfNameAlreadyExistsInTable : function(currentNameValues)
{
for(var i=0; i < currentNameValues.length ; i++)
{
if(document.getElementById("tbName").value == currentNameValues[i])
{
var nameVal = "Name already exists in table!";
document.getElementById("nameVal").innerHTML = nameVal;
return false;
}
}
document.getElementById("nameVal").innerHTML = "";
return true;
}
};
}();
And I have another file, lets say script.js
Is there some way to call function validateIfNameAlreadyExistsInTable from some script.js function?
The problem is that it is undefined when I try to call it:
I have index.html where I am referencing both .js files like this:
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="validationScript.js"></script>
Yes, because the IIFE returned an object that exposes the function, and the file saves that object as ValidationNamespace, which is a var declared globally and thus a global variable.
So:
ValidationNamespace.validateIfNameAlreadyExistsInTable(theName);
Re your edit, you probably want to load the scripts in the other order, first validationScript.js then script.js:
<script type="text/javascript" src="validationScript.js"></script>
<script type="text/javascript" src="script.js"></script>
Scripts are loaded and run in the order you give them (unless you use async or defer). So unless your code in script.js is waiting for some other event, it'll run before validationScript.js is loaded.
I think this should work.
ValidationNamespace().validateIfNameAlreadyExistsInTable(theName);

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.

Calling a function from an object to another javascript file

I have an object and lets call this object game.Door.
Inside this object I have a method.
openDoor: function() {
game.removeRoom1();
game.viewRoom3();
},
removeRoom1() is in this js file.
viewRoom3() is in another js file.
My HTML:
<script src="js/viewRoom3jsfile.js"> </script>
<script src="js/filewithObject.js"></script>
viewRoom3() is not working unless I put it in the same js file as my object.
Is there any way to have viewRoom3() in another js file?
Further clarification:
filewithObject.js:
var game = game || {};
game.Door = {
openDoor: function() {
game.removeRoom1();
game.viewRoom3();
},
};
game.removeRoom1 = function(){
}
viewRoom3jsfile.js:
game.viewRoom3 = function(){
}
Currently, my viewRoom3() is in the same file as my object and my javascript works.
However, if I move viewRoom3() into a seperate js file, the function stops working.
As i understand it you have something like this:
var Game= {
removeRoom1: function() { return something; },
viewRoom3: function() { return something; }
}
So the function is inside the object. If you want the function to be in another js file other than the object, i suggest you do something like this:
var Game= {
....//object code here
}
//the following can go to another js file
function removeRoom1(obj) { return obj.something; }
function viewRoom3(obj) { return obj.something; }

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