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?
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.
<script type='text/javascript' >
var myFunctionTag = false;
</script>
<script type='text/javascript' src='js/helpers.js'></script>
...
<script type='text/javascript' >
// rest of your code, which may depend on helpers.js
</script>
The variable can be declared in the .js file and simply referenced in the HTML file.
My version of helpers.js:
var myFunctionWasCalled = false;
function doFoo()
{
if (!myFunctionWasCalled) {
alert("doFoo called for the very first time!");
myFunctionWasCalled = true;
}
else {
alert("doFoo called again");
}
}
And a page to test it:
<html>
<head>
<title>Test Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="helpers.js"></script>
</head>
<body>
<p>myFunctionWasCalled is
<script type="text/javascript">document.write(myFunctionWasCalled);</script>
</p>
<script type="text/javascript">doFoo();</script>
<p>Some stuff in between</p>
<script type="text/javascript">doFoo();</script>
<p>myFunctionWasCalled is
<script type="text/javascript">document.write(myFunctionWasCalled);</script>
</p>
</body>
</html>
You'll see the test alert() will display two different things, and the value written to the page will be different the second time.
OK, guys, here's my little test too. I had a similar problem, so I decided to test out 3 situations:
One HTML file, one external JS file... does it work at all - can functions communicate via a global var?
Two HTML files, one external JS file, one browser, two tabs: will they interfere via the global var?
One HTML file, open by 2 browsers, will it work and will they interfere?
All the results were as expected.
It works. Functions f1() and f2() communicate via global var (var is in the external JS file, not in HTML file).
They do not interfere. Apparently distinct copies of JS file have been made for each browser tab, each HTML page.
All works independently, 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:
var global = 0;
function f1()
{
alert('fired: f1');
global = 1;
alert('global changed to 1');
}
function f2()
{
alert('fired f2');
alert('value of global: '+global);
}
HTML 1:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>
HTML 2
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index2.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>
Hi to pass values from one js file to another js file we can use Local storage concept
<body>
<script src="two.js"></script>
<script src="three.js"></script>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>
Two.js file
function myFunction() {
var test =localStorage.name;
alert(test);
}
Three.js File
localStorage.name = 1;
//Javascript file 1
localStorage.setItem('Data',10);
//Javascript file 2
var number=localStorage.getItem('Data');
Don't forget to link your JS files in html :)
If you're using node:
Create file to declare value, say it's called values.js:
export let someValues = {
value1: 0
}
Then just import it as needed at the top of each file it's used in (e.g., file.js):
import { someValues } from './values'
console.log(someValues);
I think you should be using "local storage" rather than global variables.
If you are concerned that "local storage" may not be supported in very old browsers, consider using an existing plug-in which checks the availability of "local storage" and uses other methods if it isn't available.
I used http://www.jstorage.info/ and I'm happy with it so far.
You can make a json object like:
globalVariable={example_attribute:"SomeValue"};
in fileA.js
And access it from fileB.js like:
globalVariable.example_attribute
You can set
window['yourVariableName'] = yourVariable;
and it will make that variable global for all the files.
Related
I was setting up a basic website, but for some reason when I went to test it I was confused to find that it wasn't quite working like usual. I keep getting this error.
"Uncaught ReferenceError: revealMessage is not defined"
<!DOCTYPE html>
<html>
<head>
<script src="js/script.js"></script>
<title>Rock Paper Scissors!</title>
</head>
<body>
<button onclick="revealMessage()">Click!</button>
<p id="hiddenMessage" style="display:none">hidden message thingy</p>
</body>
</html>
function revealMessage() {
document.getElementById("hiddenMessage").style.display = "block";
}
The only thing I can see that could be a possible issue is if your JavaScript file is not within a folder named "js". You said that your js is in another folder; if it is named anything other than "js", then your html file is trying to access the JS file within a folder that does not exist. So your file structure should look like
- [html file name].html
- js/
- script.js
Your two snippets were disconnected. Just put HTML and JS code into same snippet and it should work. See below:
function revealMessage() {
document.getElementById("hiddenMessage").style.display = "block";
}
<!DOCTYPE html>
<html>
<head>
<script src="js/script.js"></script>
<title>Rock Paper Scissors!</title>
</head>
<body>
<button onclick="revealMessage()">Click!</button>
<p id="hiddenMessage" style="display:none">hidden message thingy</p>
</body>
</html>
Looks like there is no problem with the code but just check if your function is in global scope or local scope.
Also make sure that your js file is linked to your html properly. Check your js file with a basic alert();
I would like to have many HTML pages of one type, the only difference being the page title and some data stored in different .json files. Everything else should be stored in two centralized files, a .js and an .html file. In pseudocode the pages should look like this:
<html>
<head>
include global_script.js
include specific_data_n.json
</head>
<body>
include global_body.html
</body>
</html>
where the n-th page includes the data file specific_data_n.json but everything else is always the same.
I know how to include .js and .json files in the header. However, I don't really know how to include the .html file in the body. I searched on the net and, in particular, found this question: Server side includes alternative I tried different ways of including the body proposed in the answers but whatever I tried, I got a JS error.
Here is a minimal example of the problem. First, the working file where the body is in the main file and not in an extra file:
function init(){document.getElementById('demo').innerHTML = '2+2=4';}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><head>
<script language="javascript" type="text/javascript" src="minimal.js"></script>
</head>
<body onload="init();">
<div id="demo">
2+2=5
</div>
</body>
</html>
Now I tried to put the body in an external file following one of the answers of the question linked above.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script language="javascript" type="text/javascript" src="minimal.js"></script>
</head>
<body onload="init();">
<!-- Content, inclusion from https://stackoverflow.com/questions/35249827/can-you-link-to-an-html-file -->
<div w3-include-html="body_minimal.html"></div>
<script>
(function () {
myHTMLInclude();
function myHTMLInclude() {
var z, i, a, file, xhttp;
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
if (z[i].getAttribute("w3-include-html")) {
a = z[i].cloneNode(false);
file = z[i].getAttribute("w3-include-html");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
a.removeAttribute("w3-include-html");
a.innerHTML = xhttp.responseText;
z[i].parentNode.replaceChild(a, z[i]);
myHTMLInclude();
}
}
xhttp.open("GET", file, true);
xhttp.send();
return;
}
}
}
})();
</script>
</body>
</html>
and the body_minimal.html which is included:
<div id="demo">
2+2=5
</div>
I also tried different further approaches for embedding the body_minimal.html file (which I can present if needed) but none of them works, so I assume that it is some fundamental problem. I always get the error in the JS debugger:
TypeError: document.getElementById(...) is null
I need to add that I have no experience neither in HTML nor in CSS and am mostly copy&pasting stuff from different tutorials, forums and Q&A sites so I do not really understand what this code for the embedding of the HTML file is doing. :)
Thanks for any hint on what the problem might be and a happy new year!
This really belongs as a comment but unfortunately my account is new so I'm not allowed...An answer will have to do.
If your webhost runs PHP I'd suggest looking into PHP includes, they're much simpler.
Basically, you would save your central html file as a .php file instead and include the HTML file you want using
<?php
include 'global_body.html';
?>
Found a solution which looks stupid, but as you know, if something looks stupid but works, it isn't stupid. :) I just made another .js file which writes the body contents via document.write():
<!DOCTYPE html>
<html>
<head>
<script language="javascript" type="text/javascript" src="script.js"></script>
</head>
<body>
<script language="javascript" type="text/javascript" src="body.js"></script>
</body>
</html>
And the included .js files:
//body.js
document.write('<div id="demo"->2+2=5</div>');
and
//script.js
document.getElementById('demo').innerHTML = '2+2=4';
The only problem is that in a real world scenario the contents of the body are many lines and JS needs a backslash on each line break. Also, the syntax highlighting only shows all the HTML code in one colour as from JS's point of view it is just a string. Therefore I'm still interested in better/cleaner solutions!
Is it possible with javascript/jQuery to create objects on page load (or (document).ready) and then later use them, for example on keyup on an input.
If so, how?
If you put all code in $(document).ready{all code here} then your variables won't go out of scope.
$(document).ready(function(){
var someObject={};
$("selector").click(function(e){
console.log(someObject);
});
});
If you're using onclick in html then I'd advice you to change that and move all JS code to JS file or <script> block (not in your html).
Instead of putting many variables on global scope you can namespace it (if you can't put all code in $(document).ready).
var myApplication = myApplication || {};//if myApplication doesn't exist then create it
myApplication.someObject = {};
Then even if your JS is spread over several files you can still maintain one myApplication object.
As gp mentioned; you can use data to add data to html elements:
$("#somebutton").on("click",function(e){
$(this).data("someObject",{});// you can use e.target instead of this as well
});
Below find a example usage.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
TODO write content
<div id="MytextID">My text </div>
<input type="text" id="inputId" name="name">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var x = $('#MytextID');
$('#inputId').keyup(function(){
alert(x.text());
})
})
</script>
</body>
</html>
I have just started learning Javascript and Ok here is a code I want to try and see it in the browser, so I create a test.js file and put this in it:
function useless(callback) {
return callback
}
var text = 'Amigo';
assert(
useless(function(){ return text; }) === text,
"The useless function works! " + text);
But still there is more, I should write a minimum HTML page than can call this function, What is sample HTML to host this method in it?
I have written something like this but still there is something wrong with it:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script src="hehe.js" >
useless('Amigo');
window.onload=useless('Amigo')
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="hehe.js"></script>
<script >
useless('Amigo');
window.onload=useless('Amigo')
</script>
</body>
</html>
You can load the source in a separate script from the inline one that you call it in. Note that this assumes that hehe.js is in the root directory of your site.
For testing js in general jsFiddle is a nice resource that lets you define your html/js/css and experiment with small changes without having to write out all the files.
I have a normal html site, it defines a variable called myVar. This is the declaration:
var myVar = something_that_is_set_dynamically;
Now I have a js file and I need to get the value of myVar in that file. How would I do that?
Thanks!
Make sure you have added the javascript file after you have declared your myVar.
For instance:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title></title>
</head>
<body>
<script type="text/javascript">
var myVar = "foobar";
</script>
<script type="text/javascript" src="yourJsFileUses-myVar.js"></script>
<!-- you cannot declare myVar here, because "yourJsFile.js" is already
being executed, so you have to declare your myVar before you include
your javascript file -->
</body>
</html>
In your script:
do_something_with(myVar);
And make sure the <script> that uses it appears after the <script> that defines it, or doesn't use it outside of a function that isn't run under the defining <script> has been processed.
The only impact that putting something in a different file (or inline script element) has, is that it won't be available under the browser has parsed it. The first script will run before hoisting has been applied to the second script.
Include the file in your HTML page's header:
<script type="text/JavaScript" src="yourfile.js"></script>
If the variable is global (i.e., it is not declared inside a function) it will be visible to your whole page.