Cannot import js into html [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
I am just trying to get into the absolute basics of JS and HTML. Basically I want to execute a super simple js.
Here's my test.js file:
document.getElementById("test").innerHTML = "Loaded js file";
Here's my test.html:
<!DOCTYPE HTML>
<html lang="de">
<head>
<title>Testing page</title>
<meta charset="utf-8">
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<p id="test">Not loaded</p>
</body>
</html>
Both files are located in the same folder. What should happen is that the "Not loaded" text gets replaced by "Loaded js file", but it just doesn't happen. What am I doing wrong?

This is because the JavaScript loads before the element does. You have two ways.
Quick and Dirty way
Move the JavaScript after the element.
<!DOCTYPE HTML>
<html lang="de">
<head>
<title>Testing page</title>
<meta charset="utf-8" />
</head>
<body>
<p id="test">Not loaded</p>
<script type="text/javascript" src="test.js"></script>
</body>
</html>
Using Event Handler
Or, use document's load event handler in the JavaScript.
$(function () {
document.getElementById("test").innerHTML = "Loaded js file";
});
Since you are using jQuery, you can keep it in a simple way:
$(function () {
$("#test").html("Loaded js file");
});
Note: I prefer this method to the above method, as this function gets executed only when the document is loaded fully and it is unobtrusive as well.

That's because you have to wait until the window has been loaded.
window.onload = function() {
document.getElementById("test").innerHTML = "Loaded js file";
};

The elements of the DOM are parsed in a sequential order.
The script is an element too. In your case the script has been parsed but the p element has not been parsed yet, because the execution of the script stops all HTML parsing until it reaches the end of the file.
Therefor your script should be replaced at the bottom of the file in order to query the DOM.
<!DOCTYPE HTML>
<html lang="de">
<head>
<title>Testing page</title>
<meta charset="utf-8">
</head>
<body>
<p id="test">Not loaded</p>
<script type="text/javascript" src="test.js"></script>
</body>
</html>
or place the script at the top, but wait for the to dom load event
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("test").innerHTML = "Loaded js file";
}, false);

Script is loaded before DOM's are ready, when you setting innerHTML, DOM object #test not exist yet.
Solution - wrap js content in function onload:
window.onload = function() {
document.getElementById("test").innerHTML = "Loaded js file";
};

Related

How to get multiple Jquery scripts to work together

I'm trying to run two Jquery scripts, one called balancedgallery and the other museum. When I run each script by themselfs they run fine but together the balancedgallery script doesn't allow the Museum script to link the viewer and instead links directly to the image.
This could be because they are old scripts from 2014 and 2017 and some standards have changed? I had to update the ".load" to ".on('load')" for the balanced gallery reference. Though both the scripts are running fine (with no console errors). If I put "#msm-gallery-2" at the end of the url (2 being the image number) the viewer (Museum) displays.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>Title</title>
<meta name="viewport" content="width=device-width" />
</head>
<body>
<div id="content">
<img src="https://www.ryanepp.com/assets/demos/balanced_gallery/moped1.jpg"/>
<img src="https://www.ryanepp.com/assets/demos/balanced_gallery/moped2.jpg"/>
<img src="https://www.ryanepp.com/assets/demos/balanced_gallery/moped3.jpg"/>
</div>
<script src="https://code.jquery.com/jquery-3.6.1.js"></script>
<script src="https://cdn.jsdelivr.net/gh/enzzzooo/balanced-gallery/jquery.balanced-gallery.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/enzzzooo/museum/jquery.museum.js"></script>
<script>
$(document).ready(function() {
$.museum($('#content img'));
});
</script>
<script>
$(window).on('load', function () {
$("#content").BalancedGallery({});
} )
</script>
</body>
</html>
Not sure if this is affecting your scripts at all, but you have an unclosed tag on line 1 - set this to <!DOCTYPE html> <html lang="en-US">
and your last "img" tag is unclosed, which could be merging the div holding the scripts inside your last image.

Call a script from .js instead of html

I would like to convert this html script into a chrome extension. I followed this short tuto and apparently, I should move all the script ●parts into a .jsfile:
Due to security constraints, we can’t put inline JavaScript into our
HTML files inside of our Chrome extensions, so we have to create a
separate file to hold any JavaScript code we need and we’ll reference
it from the HTML file.
So instead of having just this html:
<!DOCTYPE html> <html>
<head>
<title>My Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body>
<div class="translate">Тестирование</p>
<div class="translate_control" lang="en"></div>
<script>
function googleSectionalElementInit() {
new google.translate.SectionalElement({
sectionalNodeClassName: 'translate',
controlNodeClassName: 'translate_control',
background: '#f4fa58'
}, 'google_sectional_element');
}
</script>
<script src="//translate.google.com/translate_a/element.js?cb=googleSectionalElementInit&ug=section&hl=en"></script>
</body> </html>
I should have one html ...:
<!DOCTYPE html>
<html>
<body>
<div class="translate">Тестирование</p>
<div class="translate_control" lang="en"></div>
</body>
</html>
...and one .js. But I am not sure how to go with the .js. How shoudl I call the script //translate.google.com/translate_a/element.js?cb=googleSectionalElementInit&ug=section&hl=en. Also should I add the function googleSectionalElementInit inside a document.addEventListener function?
Also will the script work because it will be stored on my local computer and not a server?

How to link JavaScript file to HTML [duplicate]

This question already has answers here:
Javascript can't find element by id? [duplicate]
(5 answers)
Closed 3 years ago.
I am creating a very simple HTML file and I am trying to link it to a JavaScript file so that the text changes when I click on it.
I have copied it almost entirely from W3 and it works when I place the javascript code within the HTML script tags, but when I try to source it using the script tags (see the first example below) I am not able to get the JavaScript file to link to the HTML.
Any help you can give me is appreciated. I am currently using Visual Studio Code to do this if that gives any hints as to what I am doing wrong.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>TextChange</title>
<script src="js/script.js"></script>
</head>
<body>
<p>This example uses the HTML DOM to assign an "onclick" event to a p element.</p>
<p id="demo">Click me.</p>
</body>
</html>
JavaScript
document.getElementById("demo").onclick = function() {myFunction()};
function myFunction() {
document.getElementById("demo").innerHTML = "YOU CLICKED ME!";
}
Alternate HTML that works
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>TextChange</title>
</head>
<body>
<p>This example uses the HTML DOM to assign an "onclick" event to a p element.</p>
<p id="demo">Click me.</p>
<script>
document.getElementById("demo").onclick = function() {myFunction()};
function myFunction() {
document.getElementById("demo").innerHTML = "YOU CLICKED ME!";
}
</script>
</body>
</html>
When I render the HTML and view the source and click on the .js extension, I am able to view the javascript file. Despite this, the text that I want to change when I click on it does not change if I click on it.
Your JS file is included before the element, so getElementById() returns null.
Move it after the element, or make it wait for the document's loaded event.
Your script tag must be on the bottom of your html code (before the closure of <body> tag) so your javascript can use and detect the different DOM elements after they get rendered :
<html>
<body>
<!-- your code here -->
<script src="js/script.js"></script>
</body>
</html>

How to append a whole html file with jquery

I got a html file like this,
<!DOCTYPE html>
<html lang="en">
<head>
//some content
</head>
<body>
//some content
</body>
</html>
My question is how to load this file as a whole with jquery. I tried it with
append function, but it didn't work.. I searched for the solution for quite a while, but just found a lot of methods to append some parts of html file, like meta, link, not a whole file.
Can I do it with jquery?
index.html or whatever
<iframe src="filename.html"></iframe>
filename.html
<!DOCTYPE html>
<html lang="en">
<head>
//some content
</head>
<body>
//some content
</body>
</html>
You can use <link> element with rel attribute set to import, href set to path to file, type set to "text/html". Use XMLSerializer() instance .serializeToString() with replacement document .doctype property as parameter to get <!DOCTYPE> declaration from imported document; document.write() with .import.documentElement.outerHTML property of link element as parameter to replace existing .doctype and <html> node with .doctype and <html> of imported document.
<!DOCTYPE html>
<html lang="en">
<head>
<link id="doc" rel="import" href="https://gist.githubusercontent.com/guest271314/9921cb52b143437b23f23fa32284ca35/raw/86532c043b666bce15b33c91dc29e98615dd4e25/replacementDocument.html" type="text/html" />
</head>
<body>
//original content
<button>load html document</button>
<script>
var link = document.getElementById("doc");
document.querySelector("button")
.onclick = function() {
// http://stackoverflow.com/a/30565562/
var dt = new XMLSerializer().serializeToString(link.import.doctype);
document.write(dt, link.import.documentElement.outerHTML);
document.close();
}
</script>
</body>
</html>

why jquery/javascript code doesn't work when I use it in same script tag with src attribute [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does a script-Tag with src AND content mean?
I used the following in my html page
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="resources/scripts/jquery-1.8.2.min.js">
$(document).ready(function(){
alert("ABC");
});
</script>
</head>
<body>
<p>THIS IS MY INDEX PAGE.</p>
</body>
</html>
The jquery doesn't work here meaning I don't see any effect of it after putting an alert in it.
But when I put in seperate <script> tag like the one below it works,
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="resources/scripts/jquery-1.8.2.min.js">
</script>
<script>
$(document).ready(function(){
alert("ABC");
});
</script>
</head>
<body>
<p>If you click on me, I will disappear.</p>
</body>
</html>
so if anyone any explain?
From w3schools:
http://www.w3schools.com/tags/tag_script.asp
"Note: If the "src" attribute is present, the element must be empty."
When you use script tag you can provide the source code using src attribute or inside the tag, but not both of them.
This is because, you are providing the src tag with the javascript.
The src file contents will get expanded as content of <script> (start and end) tag.
You can inspect this with firebug if you want.
What your first tag is doing is telling the browser that the content of the script is located in an external file. It will ignore any scripting in the actual tag in favour of the contents of the file.
You need to use the separate tag.
I don't know . But if the source you assigned in "src" inside the tag is a online one.
If you save go to that source and copy the script and save it in your local. Then
assign the "src" of your local one then it will work. ie.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="../polin/jquery_library.js">
function fn()
{alert("pp");}
</script>
<script type="text/javascript">
$(document).ready(function(){
alert("ABC");
});
function fn()
{alert("oo");}
</script>
</script>
</head>
<body onload="fn()">
<p>THIS IS MY INDEX PAGE.</p>
</body>
</html>
src="../polin/jquery_library.js" this file is in my local where the jquery source script is saved. And it work

Categories

Resources