How to link a JS file externally? - javascript

I faced this problem.The Condition needed is that the external file should not include script tag.But in order to call a function the script tag is needed.The code is a mere example.Also is there any other alternative to link the External JS file.
<!DOCTYPE html>
<html>
<body>
<script src="Friendship.js">
</script>
</body>
</html>
The code for the external JS is:
<!DOCTYPE html>
<head>
<script>
function mySpace()
{
document.getElementById("playa").innerHTML="Friendship is always a sweet responsibility, never an opportunity.
";
}
</script>
<body>
<h1><tt>Friendship</tt></h1>
<p id="playa">"One of the most beautiful qualities of true friendship is to understand and to be understood.
"</p>
<button type="button" onclick="mySpace()">Click Here !</button>
</body>
</html>

A Javascript file, should only contain JavaScript code. It should not contain HTML, CSS or any other markup.
Based on your example above, you should have the following two files:
index.html
<!DOCTYPE html>
<html>
<body>
<!-- Link to external JavaScript file -->
<script src="friendship.js"></script>
<h1><tt>Friendship</tt></h1>
<p id="playa">"One of the most beautiful qualities of true friendship is to understand and to be understood."</p>
<button type="button" onclick="mySpace()">Click Here !</button>
</body>
</html>
friendship.js
// This is a comment
function mySpace()
{
document.getElementById("playa").innerHTML="Friendship is always a sweet responsibility, never an opportunity.";
}
Notes
The friendship.js is pure JavaScript (or comments as per my example above). You should not add any HTML tags to the JavaScript file such as <html>, <body>, etc. You also do not need to include <script> tags which will generate errors.
is it possible to write the JS code without an HTML declaration
I'm not exactly sure what you mean by this, but I'll attempt to explain. If you were to visit http://www.example.com/friendship.js then you would be shown the raw JavaScript code in that file. The code would not be executed automatically. You will need to initiate the JavaScript from an HTML file itself, just as you've done in your HTML with onclick="mySpace()".

Related

A self contained Javascript/Html module - Is this possible?

[EDIT: I have possibly found another solution. Kooilnc's solution looks good. Is the solution at the bottom of this question better or worse than Kooilnc's?]
I have a div with associated javascript code. I would like to have the html for just this div and the associated javascript code all in one file, a kind of self contained 'module', eg
mydiv.html
<html>
<div id="Wibble" style="display: none;">
... loads of structure for just this div
</div>
<script type="text/javascript">
... loads of js functions just associated with this div
</script>
</html>
Then in my main page index.html I would like to include this 'module' in some way.
The only thing I have found is a Server Side Include:
index.html
<!DOCTYPE html>
<html>
<head>
... loads of stuff
</head>
<body>
... loads of other html structure
<!--#include FILE="mydiv.html" -->
... loads of other html structure and script tags
</body>
</html>
Question 1: Is there a better way of doing this?
Question 2: Should I have the html tag in mydiv.html as that will obviously put an html tag in index.html which is out of place?
Question 3: If that html tag in Q2 should not be there, how do I write the mydiv.html file so it has all the formatting and nice coloured structure in Visual Studio Code?
Edit:
Kooilnc's solution (below in the answers) looks good. Here is another solution I have found. It is working in my development environment Visual Studio Code. I need the javascript in my included html file in body's onload. Does anyone know if this solution will work on a server with my body onload requirement? Is it better or worse than Kooilnc's solution?
Jquery must be included with the normal <script> tag prior to this.
I insert this code within index.html
<!DOCTYPE html>
<html>
<head>
... loads of stuff
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</head>
<body>
... loads of other html structure
<div id="include_mydiv"></div>
<script>
$(function(){
$("#include_mydiv").load("mydiv.html");
});
</script>
... loads of other html structure and script tags
</body>
</html>
And mydiv.html did not have any <html> tags:
<div id="Wibble" style="display: none;">
... loads of structure for just this div
</div>
<script type="text/javascript">
... loads of js functions just associated with this div
</script>
You can try importing from template elements. Here is a simplified templating example that may be useful.
If you need to import from an external file, check this example I cooked up for you.
document.querySelectorAll(`[data-import]`).forEach( el => {
if (!el.dataset.imported) {
el.appendChild(document.querySelector(`#${el.dataset.import}`)
.content.cloneNode(true));
el.dataset.imported = `ok`;
}
});
<template id="someForm">
<script>
document.addEventListener(`click`, handle);
function handle(evt) {
if (evt.target.nodeName === `BUTTON`) {
alert(`Yes. I am handled`);
}
}
</script>
<button id="sub">Handle me!</button>
</template>
<template id="somethingElse">
<style type="text/css">
.red {color: red;}
</style>
<p class="red">I am appended too</p>
</template>
<div data-import="someForm"></div>
<div data-import="somethingElse"></div>
Use an Iframe
<iframe id="inlineFrameExample"
width="300"
height="200"
src="mydiv.html">
See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe

I get "function is not defined" when I move a Javascript function from in-line code, to a separate js file

I am trying to make a very simple thing work:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<script src="js/test.js" type="text/js"></script>
<button onclick="test()" type="submit">Test</button>
</body>
</html>
With js/test.js being found by the browser and containing:
function test() {
alert("test");
}
When opening the page and clicking the button, nothing happens and I can see in the console:
Uncaught ReferenceError: test is not defined
at HTMLButtonElement.onclick (test:7)
I have tried to move the script import above or under the button, or in the header.
I have tried to use "window.setlocale = function" in my js file.
I have tried to put nothing in the test method.
I checked for errors with JSLint (there is no error).
When I check the source, I can see the js file and the browser opens it when I click on it.
The only way I can get the Javascript to work is to write it inline...
Maybe the issue is with my environment?
In order to run this, I use an Apache server, and it is configured to serve this on localhost:8077. I works fine so far.
I use Laravel 7.10, PHP 7.4... working fine. To run this I created a simple route, that shows the view (a simple index.blade.php) with the HTML content copy/pasted above. It displays fine on "http://localhost:8077/test", no problem.
I also tried to use the laravel notation
<script src="{{ asset('js/test.js') }}" type="text/js"></script>
but it gives the same result.
I also have the PHP debugbar (a Laravel plugin) active, and it does not show any error. The view is properly loaded and displayed.
Also, I use PHPStorm, and it does not detect any issue.
It's been 2 days and I cannot makes this seemingly extremely basic thing to work, please help me m(_ _)m
Your script type is wrong. Use application/javascript in your script element to make your javascript work - or better yet, remove the type attribute and let browsers auto-detect the type:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<script src="js/test.js" type="application/javascript"></script>
<button onclick="test()" type="submit">Test</button>
</body>
</html>
Without type attribute:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<script src="js/test.js"></script>
<button onclick="test()" type="submit">Test</button>
</body>
</html>
you can try to add script tag to header tag. like this
<head>
<script type="text/javascript" src="path/to/script.js"></script>
<!--other script and also external css included over here-->
</head>
Try removing the function name in js/test.js
function() {
alert("test");
}
Please add the js file as a reference in the header section of your core file. External referencing.

How do you allow html and Javascript files to function in Atom?

Code on webpageThe button doesn't workSo, I am fairly new to JavaScript and have been looking at tutorials for the language. I downloaded the Atom IDE and began following a video and used the same code as the video to make a web page with a button that reveals a message when clicked. However when I click the button nothing happens, and when I hit inspect element.
It gives me the following error: Failed to load resource: net::ERR_FILE_NOT_FOUND
It appears as though the HTML file is not working with the .js file. However they are in the same directory.
Here's the updated code (still the same error):
<DOCTYPE! html>
<html>
<head>
</head>
<body>
<button onclick="revealMessage()">Click me!</button>
<p id="hiddenMessage" style="display:none">Filosofem</p>
</body>
<script>
function revealMessage() {
document.getElementById("hiddenMessage").style.display = 'block';
}
</script>
</html>
Perhaps, it is the file directory. When you declared <script src="js/script.js"></script>, that means that your script.js file, must be located in a subfolder called "js".
If you want your to be within your file, then you can do
<DOCTYPE! html>
<html>
<head>
</head>
<body>
<button onclick="revealMessage()">Click me!</button>
<p id="hiddenMessage" style="display:none">Filosofem</p>
</body>
<script>
function revealMessage() {
document.getElementById("hiddenMessage").style.display = 'block';
}
</script>
</html>
Finally, you should try resaving the code through atom, and make sure your code is the right version of your code.
By using an external stylesheet you need to make sure your CSS file is saved as said above but with <script scr="filename.js">/script> I still haven't found a way other than having your code internal which is completely fine unless you're making a world wide website then it would be easy to hack.

Script tags - not linking (JS platform game)

I'm working through the 'create a platform game' project from Eloquent JavaScript and have an issue with script tags.
In the book we're told to display our level using:
<link rel="stylesheet" href="css/game.css">
<script>
var simpleLevel = new Level(simpleLevelPlan);
var display = new DOMDisplay(document.body, simpleLevel);
</script>
I've tried adding this (together with an additional script tag for my platform.js file) into index.html but the browser is giving nothing back, not sure what I'm doing wrong?
Ensure you are inserting your scripts in the right order:
<!DOCTYPE html>
<html>
<head>
Here you should put your "included" scripts with <script src=...>
</head>
<body>
...
</body>
<script>
Here you should put your first execution, if it needs the html page been completely loaded (as to use document.body).
</script>
</html>
The scripts are being executed as they appear into the page. If you use document, you have to delay the execution until the whole page has been loaded: Either by putting your script at the end of the HTML, either by putting an initialization function within the HEAD, and call it from body onload:
<head>
<script>
function myFunction(){...}
</script>
</head>
<body onload="return myFunction()">
...
</body>
Make sure to include the external JavaScript file you need in a separate <script> tag before your inline script!

How can we call a function in a .js from a .html file

In my index.html file I have:
<button onclick="myFunction()">Click me</button>
myFunction is located in index.js
how can I call this function when the button is clicked?
You need to add the index.js file at the bottom of your HTML, right before the </body> tag:
<script src="path/to/index.js"></script>
Add to header:
<script type="text/javascript" src="index.js"></script>
Add the js file reference in your html page so its functions can be called from html page.
<script src="yourfile.js"></script>
Also give your button type="button" otherwise this button will submit the page and your function will not be called.
<button type="button" onclick="myFunction()">Click me</button>
I'm guessing you're new to this all, so I'm going to try and explain it a little bit more than the answers above.
When you got your HTML:
<html>
<head>
<title>This is the title of my page</title>
<script src='js/script.js' type='text/javascript'></script>
</head>
<body>
<button onclick="myFunction()">Click me</button>
</body>
</html>
When you see this. The <script> tag says to the browser: "Okay, there is coming up some javascript (or jQuery)" so it will look in the src attribute, to see where the javascript is found that should be loaded. When it finds it, it will load it into the html document and you will have the functions in the file ready to be used in your html document. The type attribute just says: "Okay, this script is filled with javascript". You also have type='text/css' for example when you're including a CSS script to style the HTML elements of the page.
Hope it makes sence, and I wish you luck, learning html/css/javascript. If you have any questions, reply to this answer.

Categories

Resources