A bunch of my JavaScript code is in an external file called helpers.js. Inside the HTML that calls this JavaScript code I find myself in need of knowing if a certain function from helpers.js has been called.
I have attempted to create a global variable by defining:
var myFunctionTag = true;
In global scope both in my HTML code and in helpers.js.
Heres what my html code looks like:
<html>
...
<script type='text/javascript' src='js/helpers.js'></script>
...
<script>
var myFunctionTag = false;
...
//I try to use myFunctionTag here but it is always false, even though it has been se t to 'true' in helpers.js
</script>
Is what I am trying to do even feasible?
The variable can be declared in the
.js
file and simply referenced in the HTML file. My version ofhelpers.js
:And a page to test it:
You'll see the test
alert()
will display two different things, and the value written to the page will be different the second time.Hi to pass values from one js file to another js file we can use Local storage concept
Two.js file
Three.js File
OK, guys, here's my little test too. I had a similar problem, so I decided to test out 3 situations:
All the results were as expected.
Instead of browsing tutorials, I found it easier to try it out, so I did. My conclusion: whenever you include an external JS file in your HTML page, the contents of the external JS gets "copy/pasted" into your HTML page before the page is rendered. Or into your PHP page if you will. Please correct me if I'm wrong here. Thanx.
My example files follow:
EXTERNAL JS:
HTML 1:
HTML 2
You can make a json object like:
in fileA.js
And access it from fileB.js like:
globalVariable.example_attribute
//Javascript file 1
//Javascript file 2
Don't forget to link your JS files in html :)
You need to declare the variable before you include the helpers.js file. Simply create a script tag above the include for helpers.js and define it there.