How to Load Different Javascript Files Based on Input - javascript

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

Related

Is it possible to use javascript to modify a script element?

Is there a way to use javascript to modify a script element?
Like for example:
HTML:
<script id="something" src="/js/file.js"></script>
Javascript:
var something = document.getElementById("something");
something.src = "/js/anotherfile.js"
Is it possible? Because I have a bit of code that works like that and it sort of doesn't work
To be specific, here's the code:
<!DOCTYPE html>
<html>
<head>
<title>MyohTheGod's Website</title>
<link rel="icon" type="image/x-icon" href="/supercorn.gif" defer>
</link>
<link id="css" href="/css/dark.css" rel="stylesheet" type="text/css">
</link>
<script src="/js/particles.js" defer></script>
<script src="/js/header.js"></script>
<script src="/js/theme.js"></script>
<script>window.alert("Welcome to the Home of MyohTheGod. You can play games, check out our web proxies, and more. Also, please do check out the About page. Press OK to continue...");</script>
</head>
<body>
-snip-
</body>
<script id="foot" src="/js/footer.js"></script>
</html>
<script>
-snip-
</script>
var css = document.getElementById("css");
var foot = document.getElementById("foot");
function toggleDLmode(m) {
-snip-
if (dlmodebool) {
css.href = "/css/dark.css"
foot.src="/js/dark-footer.js"
} else {
css.href = "/css/index.css"
foot.src="/js/footer.js"
}
}
-snip-
It is working, do you inspect it? It does changed, but maybe you're thinking, "hm why this /js/anotherfile.js is not downloaded?". Well because of the script tag is already rendered and already downloaded, so you can't do that. What you can do though add NEW script tag.
Maybe this will help How to dynamically change the script src?. This links would explain more why your code "does not work".
There certainly is. You can use document.scripts which returns an collection that you can iterate through like an array. You can change the code using the innerHTML property very much like a normal element. See here https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection
Edited to add: If you've got a html page with multiple script tags, the document.script collection has each script in the order they appear. The code below will log out the source (src tag) or the actual javascript for each script element.
You can also 'write' javascript by setting the innerHTML property.
IMHO it's a bit of a solution that's looking for a problem but at least it gives you access to the number of scripts you have.
[...document.scripts].forEach(script => {
if (script.src != '') {
console.log("Script source:" + script.src);
} else {
console.log(script.innerHTML);
}
});

javascript global variables undefined?

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.

The server responded with a status of 404 (Not Found)

I am trying to instantiate a class in one JavaScript file in another HTML file but I keep on getting this error.
Here is the code for the JavaScript file:
class Puzzle {
constructor(fenStart, pgnEnd) {
this.fenStart = fenStart;
this.pgnEnd = pgnEnd;
}
}
And here is the code for the HTML. It should be noted that I am also using chessboard.js and chess.js and that everything is saved in the same folder.
<!DOCTYPE html>
<html>
<head>
<title>Chess</title>
<base href="http://chessboardjs.com/" />
<link rel="stylesheet" href="css/chessboard.css" />
</head>
<body>
<script src="js/chess.js"></script>
<div id="board" style="width: 400px"></div>
<p>PGN: <span id="pgn"></span></p>
<script src="js/json3.min.js"></script>
<script src="js/jquery-1.10.1.min.js"></script>
<script src="js/chessboard.js"></script>
<script src="class.js"></script>
<script>
var pgnEl = $('#pgn');
const x = new Puzzle("test", "test");
pgnEl.html(x.fenStart);
</script>
</body>
</html>
What is causing this error and how can I fix it?
This could be a result from improper file locations, like #sideroxylon said, js/class.js instead of class.js.
"The HTML <base> tag is used to specify a base URI, or URL, for relative links." https://www.tutorialspoint.com/html/html_base_tag.htm This could be another reason your file is inaccessible.
It could also be from certain URL's being blocked. Try opening Developer Console (CTRL-SHIFT-I or F12) and looking for any errors on your page.
If you're loading over HTTPS any content from an HTTP source may be blocked. Here is your exact code (using online versions of each library) but with the class.js file loaded in as a regular script tag and including the starting <body> tag.
https://jsfiddle.net/ckazwozg/ As you should see, it is working quite well.
Edit: For convenience, here is the raw source code from the JSFiddle.
<!DOCTYPE html>
<html>
<head>
<title>Chess</title>
<link rel="stylesheet" href="https://rawgit.com/oakmac/chessboardjs/master/src/chessboard.css" />
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chess.js/0.10.2/chess.js"></script>
<div id="board" style="width: 400px"></div>
<p>PGN: <span id="pgn"></span></p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/json3/3.3.2/json3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://rawgit.com/oakmac/chessboardjs/master/src/chessboard.js"></script>
<script>
// class.js
class Puzzle {
constructor(fenStart, pgnEnd) {
this.fenStart = fenStart;
this.pgnEnd = pgnEnd;
}
}
</script>
<script>
var pgnEl = $('#pgn');
const x = new Puzzle("test", "test");
pgnEl.html(x.fenStart);
</script>
</body>
</html>
I had the same error however what I did was ensure all my files are been saved to the root folder in your case I think that's js(since all your extension points to that location) in my case I've used only the file name after giving it javascript extension (.js) e.g...

Open image using Java Script and call the function in html

I have two separate files one with my html code and with my javaScript. What I am trying to do is create a function in javascript then call that function in the html. Both files are in the same folder along with the image. I'm new to both languages and to this site so please go easy;
I would really appreciate it if someone could help me please.`
JavaScript to load image below:
var menu = new image();
menu.src = "Fitness App Entry Scrren.jpg"
function menuScreen(){
document.getElementById("menu").getAttribute("src");
}
Html code to call function:
<!DOCTYPE html>
<html>
<head>
<body src="Functions.js">
<script onload="menuScreen()"></script>
</body>
<head>
</html>
What you are doing is against the rules of HTML. First of all, <body></body> should be outside of <head></head>. You should have <script></script> in either <head></head> or <body></body>. The <body> tag should have the onload attribute set to menuScreen(), and the <script> tag's src attribute should be set to Functions.js (as John Hascall said). By the way, John Hascall is right, there is no element with the ID of "menu" so it won't work unless you create a <div> or <iframe> with the specific ID and append the image to it in your Functions.js file.
So, your JavaScript code should look like this:
var menu = new Image(); // note that the constructor is capitalized
menu.src = "Fitness App Entry Screen.jpg";
// Create a <div> with the image within it.
var division = document.createElement("div");
division.setAttribute("id", "menu");
division.appendChild(menu);
document.body.appendChild(division);
function menuScreen() {
division.getAttribute("src"); // you can use division because it has the id of menu
}
And here is your HTML code to run the page (according to the HTML5 specifications, note that):
<!DOCTYPE html>
<html>
<head>
<script src="Functions.js"></script>
</head>
<body onload="menuScreen()">
<!-- Left intentionally blank -->
</body>
</html>
Hopefully this will help you!

how to distinguish from dynamic loaded script and normal src scripts

How can I distinguish from dynamic loaded script and normal script included using src property? For example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="static.js" type="text/javascript"></script>
<script type="text/javascript">
document.getElementsByTagName('head')[0].appendChild(document.createElement('script').src = 'dynamic.js');
</script>
</head>
<body>
<script type="text/javascript">
// I want to distinguish dynamic.js and static.js script tags
</script>
</body>
</html>
Add a specific HTML5 data-* attribute to the dynamic scripts:
var script = document.createElement("script");
script.setAttribute("data-is-dynamic", "true");
script.id = "script1";
script.src = "dynamic.js";
document.getElementsByTagName('head')[0].appendChild(script);
An option for getting the <head> element is to use document.head, although it's not supported in older browsers. Here's the MDN docs - https://developer.mozilla.org/en-US/docs/DOM/document.head
Then to distinguish later, use:
var someScript = document.getElementById("script1"); // or any script tag you want to analyze
if (someScript.getAttribute("data-is-dynamic") === "true") {
// is dynamic
} else {
// is static
}
Of course, at the same time, you can set an attribute on static script tags, like data-is-static, and then check for that in the opposite manner.
This allows you to validly set a "flag" on a script tag that you can retrieve later.

Categories