Pass variables between different .js files; inside the same html file - javascript

can anyone help me to pass variables from one .js file to another one, the two .js are instantiated in the same html as following:
<script src="file_1.js"></script>
<script src="file_2.js"></script>
the content of "file_1.js" is like this:
var paragraph = readFile('file_to_read.tcl');
so what i need, is to use the "paragraph " variable in side the "file_2.js script
Great thanks in advance

You can save them locally like this:
file_1.js:
window.paragraph = readFile('file_to_read.tcl');
file_2.js:
setTimeout(function(){ //a small timeout to let the variable be declared...
alert(window.paragraph);
}, 100);
Codepen

Related

Send data across two pages using JavaScript

I am a .NET stack developer and I am not so strong in JavaScript. I want to pass a variable defined in the script tag of one html page and retrieve it in a different page. By the time execution control gets to the second page, the value assigned to the variable has been lost and subsequently testVar is null. I'm trying to achieve something similar to this:
In C# I would define a static global variable to achieve this.
HTML Page 1:
<script>
var someVariable = "Hello Word";
</script>
HTML Page 2:
<script>
var testVar = someVariable;
//Expecting testVar to be assigned with Hello World
</script>
You could store your variable in the global window object.
var someVariable = "Hello Word";
window.stored_value = someVariable;
The window object is global, so just use it in another script.
HTML Page 2:
<script>
var testVar = window.stored_value;
</script>
Please have a look at a similar issue:
Storing a variable in the JavaScript 'window' object is a proper way to use that object?
You'll most likely need to look into the postMessage API, but without knowing more about the two windows and how they are related to each other (was one opened by clicking on a link in the first, for example) it's hard to give you more direction.
Inother to access external javascript in your html file, create a separate .js file e.g script.js and define someVariable in it then add the script to both html files via the script tag as so <script src="script.js"></script>.
In the script.js file add the code:
var someVariable = "Hello Word";

How do I overcome a "function is not defined" error when loading an external .js file?

I'd like to create a JS plugin (with ES6) so that it can be called from an HTML file, like this:
<div id="emails-box"></div>
<script src="emails-box.js"></script>
<script>
const container = document.querySelector('#emails-box')
EmailsBox({container, ...options})
//some code
</script>
and it can be used independently.
What the EmailsBox will do is to take the container and add a children div with a box to store a bunch of emails.
I've tried to do this for 2-3 days, but everytime I try to load the .js file, I get a:
EmailsBox is not defined
I'm getting desperate. Could you someone give me some light? Thanks!
EDIT: In my emails-box.js file, I could have something like this:
var EmailsBox = function(obj){
console.log("EmailsBox called")
// some code
return true;
}
Worked fine for me. Make sure that emails-box.js is in the same folder as index.html and the name matches the one you're linking to. working setup
Most likely the file path of your .js file is referenced wrong. So first make sure that you referenced file right. If it is, then try to define function like don't assign it to variable, it might not be defined on load page.
function EmailsBox(obj){
// some code
}
And if you really need it assigned to variable try using ready function.
var EmailsBox = function(obj){
console.log("EmailsBox called")
// some code
return true;
}
<script>
(function() {
EmailsBox({container, ...options})
})();
</script>
When calling the function, make sure options variable is defined.
So that instead of calling:
EmailsBox({container, ...options});//when options is not defined,
define options first and then call the EmailsBox function like so:
var options = 'hello'; //for example
EmailsBox({container, ...options});
If your emails-box.js file is properly referenced, it should work just fine.
There is a good chance that the problem with your source but if its because its not loading which would be weird then try using js to load the script if this doesn't work its wrong for sure and you should check it is right
var source = 'source here to script file';
var script = document.createElement('script');
script.onload = function () {
//what you want to do with this script
};
script.src = source();
document.head.appendChild(script);

How to access objects in an external js file from another external js file

Hello fellow programmers,
I am wondering today how to access objects from another external js file. I'm using this as a way to organize my code throughout multiple js files. Here's an example of what I'm trying to say.
Imagine this as the code from an external js file:
$(function () {
function Person() {
this.name = "Bob";
}
})
And I want to access that object in another js file:
$(function () {
var person = new Person;
alert(person.name);
})
Is there a way to do something like that? How would I need to position the html?
My first wonder is why you have your JS wrapped in a function like so. You can see here I've accessed "hello" from another script loaded after it's set - as it's set in the global space.
https://jsfiddle.net/sj7bp97c/
<script src="https://pastebin.mozilla.org/?dl=8907696">
</script>
<script src="https://pastebin.mozilla.org/?dl=8907697">
</script>
One script sets the value, the other prints it to console. Unless it's required for your Javascript to be surrounded by functions, I'm not sure why you're doing so.
Reveal the function to the global scope:
$(function () {
function Person() {
this.name = "Bob";
}
return {
Person: Person
}
})()
When revealed to the global scope, you access it from within another JavaScript file as soon as the script has initiated. So you'll want to include it after you included this one.
You just need to mention both of your js script files in head section of html.
Javascript will take care rest of the things.
<head>
<script src="First.js"></script>
<script src="Second.js"></script>
</head>

How to access a variable among multiple javascript files

Currently i have 2 html pages and 2 java script pages,say
h1.html,h2.html
j1.js,j2.js
where can i declare a variable so that the variable can be accessible between both of java script and html files
i want to initialize a value to that variable in first java script file and access that value in the second java script file
if you want to access variable values across two html files even after the page loads you can use localStorage in js.
say if you want to set a value for a variable localStorage.setItem("newvariable", 'variablevalue'); and for getting value use this var getValue = localStorage.getItem("newvariable");
EDIT:
for your base question refer those js files one by one
<script src="j1.js"></script>
<script src="j2.js"></script>
you can declare the variable in any javascript file, and just include the file next to the other javascript file forexample.
// for example if you have file1.js like this.
var myvalue = 25;
You can then save this file and include it in your main or other html files for example at the bottom of your html document.
<html>
<body> </body>
<script src='file1.js'></script> // put the javascript file with your variable declaration on top of the other file you want to access the value from.
<script src='file2.js'></script>
</html>
after the above you can then just print the variable in 'file2.js' like this.
// inside file2.js
console.log(myvalue) // which was declared in the 'file1.js'
hope this helps.
You can bring your javascripts in to the <head> of your html then you can refer to the javascript as a function passing values as a parameter and returning data as well.
PS Don't forget to declare the javascript on your form.

How can I have the same javascript variable on the same page?

Our service offers the ability to drop in some javascript on your page and display some tracking data, but I'd like for customers to be able to embed multiple instances of the embed code on the same page.
The problem right now is that I can't include the same variables names on the page.
For instance:
<script type="text/javascript">
var ttp_number = "1Z8E26R80281495993"; // Tracking number
var ttp_key="123456";
(function(){
document.write('<div id="ttp"></div>');
s=document.createElement('script');
s.type="text/javascript";
s.src="http://c.trackthepack.com/j/e?" + Math.random();
setTimeout("document.getElementById('ttp').appendChild(s);",1);
})()
</script>
Then if they wanted to be able to embed that again, I'd have to change all variable names:
<script type="text/javascript">
var ttp_number_001 = "446888240962"; // Tracking number
var ttp_key_001="123456";
(function(){
document.write('<div id="ttp_001"></div>');
s_001=document.createElement('script');
s_001.type="text/javascript";
s_001.src="http://c.trackthepack.com/j/e?" + Math.random();
setTimeout("document.getElementById('ttp_001').appendChild(s_001);",1);
})()
</script>
I'm okay with having them change the contents of the function() block, but the ttp_number and ttp_key need to stay the same variable name.
Right now, when I have multiple embeds on the page, they all inherit the contents of the variables in the last embed code.
So, the ultimate question here...how do I fix that?
Maybe store the ttp_key and ttp_number's in arrays instead?
Why not declare the variables in the function body. Then they're only scoped to that function. You can still set them to different values when you dump the script into the HTML.
I know you mention/imply that the user can edit the function (for some reason) but that just seems like a world of hurt to me, so I'm hoping that that's not actually the case.
Why are you cachebusting with Math.random()? Does the JavaScript at http://c.trackthepack.com/j/e change often? If not, you should let the cache do its job.
But if so, could you make it dynamic enough to inspect the arguments it's called with and use those arguments directly, instead of relaying them via the global window object, so that you load http://c.trackthepack.com/j/e?n=446888240962&k=123456 and it doesn't have to look them up when the script runs?

Categories

Resources