I've JavaScript file named Second.js which contains variable named page.
Second.js:
var page = 1;
How can I retrieve that value, i.e page, from another JavaScript named one.js?
An other way to get a value from another .js file is saving the variable in the browser:
a.js
var myemail="[email protected]";
localStorage.setItem("email",myemail);
Now this variable is saved in browser. If we want to get this variable in another file we use:
b.js
var x=localStorage.getItem("email");
alert(x) // [email protected]
If you really want variable visibility between different scripts you can attach the variable on the window. e.g:
script 1:
window.page = 1;
script 2:
alert(page);
Make sure you don't use very simple variable names (e.g such as page) to avoid possible collisions. A good practice is to attach an array of your application name on the window and work with that, being sure that you'll not affect anything on the "global scope". e.g:
window.MY_APP = {
page: 1,
foo: 'bar',
whatever: [1, 2, 3],
example: {
name: 'john',
surname: 'smith'
}
};
var page = 1; is the same as window.page = 1 given the former is stated outside of a functiondelete the latter but not the former. :-)All JavaScript on the page executes in the same overall environment, so if page is a global in Second.js, you can use it from any other JavaScript you load on the page. E.g.:
<script src="Second.js"></script>
<script src="SomeOtherFile.js"></script>
Provided, again, that page is a global, you can use it from SomeOtherFile.js (just referencing it as page, no qualifiers).
Or even:
<script src="Second.js"></script>
<script>
alert(page); // "1"
</script>
If page isn't a global, then you'll have to modify Second.js in some way to make the page variable or value available to other scripts. You can do that by making it global, of course, or you can use an Asynchronous Module Definition loader to avoid having bunches of globals around and manage dependencies. (AMD may be overkill for what you're doing, or not, we don't have a lot of context here.)
$(function(){.. on both pages. I was able to get the code (var) from the first page if I put the code before the ready handler but I was not able to do it if I had var something inside the ready handler in the first page. To help with that on the first page instead of using var something I used window.something and I was able to access the code that was on the first page. Any comments on that? Thanks. I found this out the hard way.There are two ways of doing this: load the scripts in the order you want to access them, or don't start executing your scripts until the page the has loaded (recommended, as this ensures that everything is definitely loaded!). Either way you can reference your variables as if they were in the same file - you do not need to re-declare them with 'var'.
Second.jsfirst or loadone.jsfirst and use your variable fromSecond.jsafter load ofSecond.js(Like page load or button click)