How to access a variable among multiple javascript files - javascript

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.

Related

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

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

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";

Use TAL:defined variable in javascript

I'm creating a page template for a plone-based website. I've defined some variables using the template attribute language:
<tal:macro metal:define-macro="sample" tal:define="var python: here.getThisVar();">
Now I would like to use var in an extern javascript file, that I call by clicking a button inside my template. How can I transfer my variable, that I can work with it in my javascript file?
In your template define a javascript variable by writing it out using TAL like this:
<script type="text/javascript" tal:content="string:var MY_VAR=${view/myVar};"></script>
Now MY_VAR should be available in scope of your external js as long as you call it after the line above...
Another way: inject your variable into HTML using an HTML 5 data attribute::
<div id="myVar" tal:attributes="data-myVar python:here.getThisVar();">
Then read it using JAvaScript/jQuery::
$('#myVar').data('myVar');
There are a variety of ways to do it. All involve constructing Javascript code as if it's text, then returning the result for insertion into a page or rendering as a JS resource in the javascript registry.
If you'd like a robust example that includes provisions for message translatability and works with the JS resource registry, see the way Plone itself does it: https://github.com/plone/Products.CMFPlone/blob/4.2.7/Products/CMFPlone/browser/jsvariables.py

Defining Django context variable in Jquery giving me error?

I am trying to use a django context variable in my jquery script.
First of all, this WORKS:
index.html
<head>
<script type="text/javascript">
var page_size = {{page_obj.paginator.num_pages}};
</script>
<script type="text/javascript" src="{% static 'js/paginate.js' %}"></script>
</head>
js/paginate.js
$(document).ready( function() {
alert(page_size); //THIS WORKS!!!
});
However, I didn't want the users to be able to be view my variables so I simply added the global variable declaration in my "paginate.js" file:
index.html
<head>
<script type="text/javascript" src="{% static 'js/paginate.js' %}"></script>
</head>
js/paginate.js
var page_size = {{page_obj.paginator.num_pages}}; //Exactly the same as the above!!
$(document).ready( function() {
alert(page_size); //ERROR!!!
});
Strangely enough, this gives me an error:
SyntaxError: invalid property id
var page_size = {{page_obj.paginator.num_pages}};
I have no idea why the first one works while the second one gives me an error, because they are exactly the same... Maybe because I'm second one is declaration in Jquery..?? Any idea??
Thanks..
TL;DR
You can't pass a variable to a static files because they aren't parse by the Django template processor.
Explanations
Your first example works because you set the {{ page_obj.paginator.num_pages }} in your template, which will be parsed and transform into a number. When you're returning a template with Django (through any render method), only the template will be rendered. CSS and Javascript linked in your template are called static files: that means they're ressources which will not be read by the Django template processor.
Imagine that you want to insert your variable in an img in your page. Does it makes any sense? No? However, it's the same behavior.
How to do this then?
You can get the data either via an AJAX request in your Javascript file (warning: a bit overkill for your case here), or using your first method.
Related topic:
Passing Python Data to JavaScript via Django
Passing parameters to the Javascript code on a page using django templates?
In Django, if we need to pass variables from a view to a JS/html file, we'll have to ensure that the file is parsed by the django template engine. In other words the file has to be served by Django.
Whereas here, the included Javascript isn't processed by the Django template processor on the server, so that won't work.
If you need to pass template variables to be used in JS files, then you have to use the first method mentioned in the question i.e. create a small <script> block wherein some global variable is declared to contain those template variables. Then, any JS file can get the values by looking for the global js variable.

Is there a way to send variables to javascript files?

is it possible to do something like this
to send the value id=3 to the js file
<script src="http://site.com/js/loader.js?id=3" ....
otherwise what's the approach to do that?
No, that won't work.
Just set the variables before you load the file:
<script>var id = 3;</script>
<script src="http://site.com/js/loader.js" ....
Since all the scripts share a global namespace, you'll be able to access the id variable from inside your loader.js file.
Of course you should think about the style and implications of using global vars to achieve that. Using a global object that hold these config variables might be a cleaner approach.
If that is just a javascript file, you can just define the variable before load it.
<script>
var id = 3;
</script>
<script src="http://site.com/js/loader.js" ....
It would work, but not if your .js URL is just for a static file. If you wrote server-side code that output JavaScript, then you could output custom JavaScript based on the query string.
This is probably overkill for what you're trying to achieve.
k so this question has pretty much been answered. But there is another approach, which may or may not be suitable for you. If you want to render script conditionally or fetch a certain script for a certain id. You can declare it in a serverside script
http://site.com/js/loader.js.php?id=1
In the loader.js.php
Just use the following line in the beginning
<?
header("Content-type: text/javascript");//To declare it is a javascript file
$id=$_REQUEST['id'];
?>
//Normal js continues after this
//When you need to use the variable, just use
var id=<?=$id?>

Categories

Resources