I have 2 .js files in the html document like this:
<script type="text/javascript" src="js/1.js"></script>
<script type="text/javascript" src="js/2.js"></script>
That document also have an iframe. I have 2 .js in the iframe aswell:
<script type="text/javascript" src="js/2.js"></script>
<script type="text/javascript" src="js/3.js"></script>
So 2.js is in both documents. My plan was to make that to connect them.
I can not put 3.js in both documents because it will mess up stuff.
1.js got a variable. I want to use that variable in 3.js. But i can't figure out how to pass a variable from 1.js to 3.js.
Is this even possible?
*The variable is declared in 1.js.
You can not "pass" variables through file references. You would need to add code to pass data from the parent frame to the iframe.
If the variable is global it is
//from the iframe
var theVariable = window.parent.yourVaraibleName;
//from the parent
var theVariable = document.getElementById("iframeId").contentWindow.yourVaraibleName;
Why not using jQuery cookies to pass the variables? Even within the multiple pages. Once you pass the variable you can destroy the cookie.
jus create a global variable, don't use var keyword
myGlobal = "probably not a good idea but still";
You cannot pass variables from one js file to the other
Javascript variables are stateless so they wont be retained.
If you are using .Net then you can make use of Session variables to solve this purpose.
If you use MVC you can go for viewbag or viewdata.
If its a must then declare some variable in the homepage, then assign the value to be passed to the variable in home page and then call the function in 3.js passing this parameter.
Related
Say I have a website with a file structure like this:
index.html
main.js
modules/my-module.js
index.html contains (along with a lot of HTML):
<button id='my-btn'>My Button</button>
<script type='module' src='./main.js'></script>
main.js contains:
import { myBtn } from "./modules/my-module.js";
and modules/my-module.js contains:
const myBtn = document.querySelector("#my-btn");
myBtn.addEventListener("click", function(){
alert("Hallo from My Button");
});
export { myBtn };
Now if I click on the button I get an alert as expected.
The problem I am having is that I have some information (ie variables with values such as strings, arrays etc) in other script tags on the index.html page which I need in modules/my-module.js
I do not want to use a global variable for this because they are evil.
I thought of creating an element(s) on the index.html page with data set attributes as keys and assign values to them. The element could then be accessed from modules/my-module.js and its data set attributes would be readable. This does work when I try it but it seems a long winded way of getting access to information available on the index.html page.
It has been suggested I create a class or function returned by the module and pass data into it. The problem with that, to me, is that I am trying to keep code related to the same thing all together in the same module. If I have to pass functions out of the module to be invoked with extra data then my code base is less well organised.
Is there any other approach which would be more direct?
I have a EE template in which I use a EE global variable {global_var}.
In the same template I have a js script.
//opening js script tag
{global_var}
//closing js script tag
Inside this script I can read and use {global_var}.
But if I move the script code to a JS template and reference to it like this
<script type="text/javascript" src='{path="js/contact_form"}'></script>
the {global_var} is no more available, why?
More info: {global_var} is a user defined variable that I added to index.php
$assign_to_config['global_vars'] = array(
"base_url" => "http://www.example.com/",
"global_var" => "hello"
);
Is there a way to read EE global variables in the referenced js file?
Try to add quotation mark to the global variable when you're outputting it to the Js.
"{global_var}"
Another reason why it may not work can be either:
The variable doesn't exist in the the DB So you might need to use syncSnippert to synchronize between the two.
The template for the variable doesn't exist so you might need to create it.
I was actually going through this link. which explains how we can share global variable across multiple js. but the point is what need to be done if I am getting some variable into one js and need to pass to another one mentioned in same document after the 1st one.
approach which followed was:
Script 1 <script type="text/javascript" src="js/client.js"></script>
body added some hidden input with id myHiddenId, where values are set using client.js
Script 2 <script type="text/javascript" src="js/anotherJS.js"></script>
inside script 2 I am simply using $("#myHiddenId").val(); and using for my purpose.
I want to know whether I am following correct approach, because that hidden field may have some data which client should not get aware of. is there any other way through which I can pass the variable values across the js files ? Since I am at beginner level hence digging up some resources/books but still no luck.
If the client should not be aware of the data then you should not be using client side JavaScript. Any JavaScript executed in the browser can be debugged and viewed by the user.
You should always handle sensitive data on the server side.
Saving the variable in the JavaScript file or in the hidden element makes little difference.
Regarding using variables across files then you should be able to use any variables declared in Script 1 in Script 2 provided they are declared in the root scope and that Script 1 appears before Script 2 in the DOM.
<script> // Script 1
var root_scope = 'This variable is declared at root';
function some_function() {
// Variables not defined at root are subject to the scope they are in
var non_root = 'This is not at root';
}
</script>
<script> // Script 2
// Use the variable declared in Script 1:
alert(root_scope); // This variable is declared at root
// Note: declaring at root is the same as assigning to window
alert(window.root_scope); // This variable is declared at root
alert(typeof non_root); // undefined
</script>
I'm using jQuery Mobile Ajax navigation feature, And I need to change a variable that is defined inside external js file, So I can't put my definition before I load that js file...
So, How to change value of a variable for external javascript file after the js file is defined?
(That external js file includes events)
So this question is not duplicate of that question.
Update
My JS File contains events, something like this: $(document).on('mousemove','#main',function() { /*something*/} );
And I need that variable. Is it possible to pass variable to that?
I have tried simply changing that variable i = 5;, but I'm getting undefined error.
Update 2
The external JS file is something for some pages that are almost same, but a little different, just one or two parameters.
And I simply want to pass the parameters to that JS file. Is it possible? How?
Let's assume http://www.example.com/external.js defines variable foo, which you want to change.
<script src="http://www.example.com/external.js"></script>
<script type="text/javascript">
foo = "my new value";
</script>
This assumes that external.js defined foo in the global scope. If it's defined in an anonymous function or similar, you won't be able to change the value.
Depending on what you're doing, you can just set the variable and it'll work. Example:
// JS file
blah = "Hello";
function doSomething() {
alert(blah);
}
// HTML file
blah = "I'm a fish";
doSomething(); // alerts "I'm a fish";
Alternatively, pass the variable as an argument to relevant functions instead of using global variables.
I am currently coding in this way:
<script type="text/javascript">
var linkObj;
Is this a safe way to store data? My concern is what if a jQuery or other plug-in was to also use the variable linkObj. Also if I declare my variable like this then can it also be seen by other functions in scripts located in other js files that I include?
$(document).ready(function(){
var linkObj;
});
as long as you use the var keyword, any variable defined in that scope won't be accessible by other plugins.
I you declare a variable this way it will be accessible to all scripts running on the page.
If you just want to use it locally, wrap it in a function:
(function() {var linkObj; ... })()
However, this way nothing outside of the function will be able to access it.
If you want to explicitly share certain variables between different scripts, you could also use an object as a namespace:
var myProject = {}
myProject.linkObj = ...
This will minimize how many global names you have to rely on.
Wrap it in a closure:
<script type="text/javascript">
(function() {
var linkObj;
// Rest of your code
})();
</script>
This way no script outside your own will have access to linkObj.
Is this a safe way to store data?
This is not storing data per se, it's only declaring a variable in a script block in what I assume is an HTML page. When you reload the page in the future, it will not hold previous values.
My concern is what if a jQuery or other plug-in was to also use the variable linkObj.
That's a valid concern, like others have pointed out. However, you would expect plugins not to rely on scope outside the plug-in. This shouldn't impact a lot as good plug-in design would likely prevent this from happening.
Also if I declare my variable like this then can it also be seen by other functions in scripts located in other js files that I include?
Yes. As long as their execution is triggered after your script block gets loaded. This normally follows the order in which your script declaration appears in the page. Or regardless of the order they appear on the page if they are executed, for example, after the jQuery DOM 'ready' event.
It's common to hear that is good to avoid 'global namespace pollution', which relates to this concern. To accomplish that you can use a function to contain code, and directly invoke that function in your script block.
(function () {
var a = 1; // the scope is within the function
alert('The variable a is equal to: ' + a);
}) (); // the parenthesis invoke the function immediately