javascript global variables undefined? - javascript

Allow me to restate my problem. These are the givens:
main.html
<html>
<head>
`<script type="text/javascript" src="js/MyJS.js"></script>;`
</head>
<body>
<script>
document.getElementById("DisplayVar").innerHTML = a;
</script>
<div id="DisplayVar">
</div>
</body>
<html>
MyJs.js
var a = 1;
Nothing is displayed in the "DisplayVar" div, and the developer console says that (a) is undefined. Why is this?

You have to assign innerHTML of the "DisplayVar" div after creating it
<head>
<script type="text/javascript">
// or source to MyJS.js
var a = 1;
</script>
</head>
<body>
<div id="DisplayVar"></div>
<script>
if(document.getElementById("DisplayVar"))
document.getElementById("DisplayVar").innerHTML = a;
</script>
</body>
See codepen, I added a reference to an external js file, and used one of the variables defined there.
I also changed the position of the inline script. It should be placed after the creation of destination div element.

Related

Why does this code not work? Javascript and HTML. Please see the details

This is my HTML file.
<body>
<header>
<h3 id = "TestID"> Test </h3>
</header>
</body>
<script src = "MessagingPage.js"></script>
This is my JS file
document.getElementById("TestID").addEventListener("load", function(){
this.innerHTML("Hi");
})
document.write("Hello World");
Now, when I load the HTML, I get "Test" in the browser. However, what needs to be there is "Hi". I do not understand why this happens. Can you please help me understand? I am just getting started, so please explain in simple terms.
Thanks for taking the time to read through this :)
You have two problems.
Only elements which load external content have a load event (such as an iframe or img).
The h3 isn't loading any external content so has no load event.
Perhaps you should bind your event handler to the window.
innerHTML is a string, not a function.
addEventListener("load", function() {
document.getElementById("TestID").innerHTML = "Hi";
})
document.write("Hello World");
<header>
<h3 id="TestID"> Test </h3>
</header>
<script src="MessagingPage.js"></script>
Including the script inside <body> and updating the JS file will resolve the problem.
Here is the example of working code:
Updated HTML:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
</head>
<body>
<header>
<h3 id = "TestID"> Test </h3>
</header>
<script src = "/MessagingPage.js"></script>
</body>
</html>
Updated JS:
// MessagingPage.js
document.getElementById("TestID").innerHTML = "Hi"
document.write("Hello World");
Output:

How to Load Different Javascript Files Based on Input

I'm working on a map that will allow the user to select one of two expressions of a dataset and toggle between them. Each expressions is set up in its own .js (main_heat.js for a heatmap, main.js for proportional symbols).
My issue is setting up controls in my index.html file that will and load the selected expression based on a click. The following code doesn't throw errors, but doesn't produce the result (reloading a different expression) that I am expecting:
index.html:
<div id ="expression">
<h4>Choose your expression</h4>
Heatmap |
Proportional Symbols
</div>
<!--EXTERNAL SCRIPT LINKS-->
<script type="text/javascript" src="js/main_heat.js"></script>
<script type="text/javascript" src="js/main.js"></script>
main.js:
function changeExpression(src){
var heat = document.createElement("script");
heat.src = "js/main_heat.js";
document.body.appendChild(heat);
var prop = document.createElement("script");
prop.src = "js/main.js";
document.body.appendChild(prop);
if (src === "heat"){
loadScript("main_heat.js")
} else if (src === "prop"){
loadScript("main.js");
}
};
function loadScript(src){
var el = document.createElement("script");
el.src = src;
document.body.appendChild(el);
}
Both changeExpression and loadScript are called in an initial callback function in main.js, and I'm struggling to see why the "onclick" in index.html doesn't produce a change. Does anybody see where I'm going wrong or have an insight on what might be causing this?
There are couple of ways you can achieve what you want if you need to run different scripts based on 'onClick'.
If the size of Js files does not matter best way is to add Js files with script tags in the 'index.html' file as below.
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<div id ="expression">
<h4>Choose your expression</h4>
Heatmap |
Proportional Symbols
</div>
</body>
<!--EXTERNAL SCRIPT LINKS-->
<script type="text/javascript" src="js/main_heat.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</html>
In case you need to add those two scripts based on onClick, You can do it with a simple function as follows.
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<div id ="expression">
<h4>Choose your expression</h4>
Heatmap |
Proportional Symbols
</div>
</body>
<script type="text/javascript">
let changeExpression = function (type) {
let elem = document.createElement("script");
if (type === 'heat') {
elem.src = "js/main_heat.js";
} else {
elem.src = "js/main.js";
}
map.off();
map.remove();
document.body.appendChild(elem);
}
</script>
</html>
Hope this helps!
Missing a semi-colon at end of line loadScript("main_heat.js")
Check the paths to your scripts because they're different (in one place you omit the directory) and therefore are likely not found
Check the console for any error like net::ERR_ABORTED 404 (Not Found)
Consider adding code to check if script is already appended because every click will append it again

External JavaScript File not working when included in body of HTML page [duplicate]

I'm trying to use an external JavaScript file in order to write "Hello World" into a HTML page.
However for some reason it does not work, I tried the same function and commands inline and it worked, but not when it's using an external JavaScript file. The part I commented out in the JS file was the previous method I was trying to use. Those lines of could worked when I ran the script from the header, and inline. Thanks
Html file:
<html>
<head>
</head>
<body>
<p id="external">
<script type="text/javascript" src="hello.js">
externalFunction();
</script>
</p>
<script type="txt/javascript" src="hello.js"></script>
</body>
</html>
JavaScript file
function externalFunction()
{
var t2 = document.getElementById("external");
t2.innerHTML = "Hello World!!!"
/*document.getElementById("external").innerHTML =
"Hello World!!!";*/
}
In general, you want to place your JavaScript at the bottom of the page because it will normally reduce the display time of your page. You can find libraries imported in the header sometimes, but either way you need to declare your functions before you use them.
http://www.w3schools.com/js/js_whereto.asp
index.html
<!DOCTYPE html>
<html>
<head>
<!-- You could put this here and it would still work -->
<!-- But it is good practice to put it at the bottom -->
<!--<script src="hello.js"></script>-->
</head>
<body>
<p id="external">Hi</p>
<!-- This first -->
<script src="hello.js"></script>
<!-- Then you can call it -->
<script type="text/javascript">
externalFunction();
</script>
</body>
</html>
hello.js
function externalFunction() {
document.getElementById("external").innerHTML = "Hello World!!!";
}
Plunker here.
Hope this helps.
Script tags with SRC values do not run the contents. Split it to two script tags. One for the include, one for the function call. And make sure the include is before the call.
use onload eventListener to make it simple
<script>
window.onload = function() {
externalFunction();
}
</script>
You're trying to call the function before it has been loaded.
Place the load script above the declaration:
<html>
<head>
<script type="txt/javascript" src="hello.js"></script>
</head>
<body>
<p id="external">
<script type="text/javascript">
externalFunction();
</script>
</p>
</body>
</html>
Also you have a typo:
<script type="txt/javascript" src="hello.js"></script>
Should be:
<script type="text/javascript" src="hello.js"></script>
The script type needs to be "text/javascript" not "txt/javascript".

Client-side Javascript can appear where within an HTML document?

Client-side Javascript can appear where within an HTML document?
A. Between the <head> and </head> tags
B. Between the <body>and </body> tags
C. Both of the above
D. None of the above
Here are codes that are placed in the different parts of the HTML. Ever variation will run no matter where the script tag is placed.
1.
<html>
<head>
<title>Foo</title>
<script type="text/javascript">
alert("hello world");
</script>
</head>
<body>
</body>
</html>
2.
<html>
<head>
<title>Foo</title>
</head>
<body>
<script type="text/javascript">
alert("hello world");
</script>
</body>
</html>
3.
<html>
<head>
<title>Foo</title>
</head>
<body>
</body>
<script type="text/javascript">
alert("hello world");
</script>
</html>
If you try out all these 3 variations where the script tags are placed in different parts of the HTML, you'll see that the alert() call will still run; regardless of their position in the HTML document.
So I think the answer to your question is:
C. Both of the above
Since there is no choice that says "Anywhere within the html document"
It is a good idea to place scripts at the bottom of the element.
This can improve page load, because HTML display is not blocked by scripts loading.
You should prefer here:
I chose "C" both of the above because the "Script" can be placed anywhere between the and < / body> as well as the < head> and < / head> It appears the most logical answer to go with in this situation is "C"

Getting HTML Parent Window Won't Work. Suggestions?

I have the following two HTML Documents:
Main.html
<html lang="eng">
<head>
<title>JavaScript Example</title>
<script type="text/javascript">
var ExamId = "001A";
function open_exam()
{
window.open("exam.html")
}
</script>
</head>
<body>
<input type=button value="Open Exam" onclick="open_exam()">
</body>
</html>
Exam.html
<html lang="eng">
<head>
<title>JavaScript Example</title>
<script type="text/javascript">
function setParentInfo()
{
window.parent.document.ExamID = '001B';
}
</script>
</head>
<body>
<p>Welcome to the Exam!</p>
<input type=button value="Set Parent Info" onclick="setParentInfo()">
</body>
</html>
Main.html brings up Exam.html via the input button. From inside Exam.html I would like to change the variable ExamID on the parent document (i.e.: Main.html). I'm trying to do this via the JavaScript function: setParentInfo().
The above code is not working. Can someone help me come up with the correct code?
Thanks So Much!
Variables are assigned on the window object, not the document object.
Since the value is already set, you can instead read the existing value to verify it:
alert(window.parent.ExamId); // == "001A"
Variable is declared and assigned in parent window so you get reference from your child window.
you can test using alert statement:
alert(window.parent.document.ExamId);
//output::001B

Categories