[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
Related
I'm trying to load a .txt file into my simple html page. I'm very noobish and all the code i got is stolen from stackoverflow.
The text file is in the same folder as the html file and contains some text that I'd like to have shown in a div and not just loaded in at the start but dynamically updated (in a 1 sec interval).
The Page that results from the code is just empty.
I am using Chrome 73.
I only use the html file and the txt file. No other files are in the folder.
<html>
<head>
<script type="text/javascript">
setInterval(read,1000);
function read(){
jQuery.get('file.txt',function(data){$('#container').html(data);});
}
read();
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
I don't know what's wrong with this code. Am I missing libraries? If you came up with a completely new code that would be appreciated as well.
Yes, you are missing the jQuery library. Try it like this and let me know:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
function read(){
jQuery.get('file.txt',function(data){$('#container').html(data);});
setTimeout(function(){read() },1000);
}
read();
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
Reference:
https://stackoverflow.com/a/24320973/1447509
See note in italics at very bottom of this article
what about a simple jQuery Load ?
$("#container").load("file.txt");
http://api.jquery.com/load/
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.
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()".
I'm sure this is a fairly basic question, but I'm relatively new to jQuery so was hoping someone might be able to help.
Basically, I need to load an HTML snippet into a page. This works fine when the snippet contains just HTML, but not when it contains a script.
I've stripped down my code to the bare minimum for clarity. This is index.html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<h1>Heading</h1>
<div id="banner"></div>
<script>
$(document).ready(function(){
$('#banner').load('banner.html');
});
</script>
</body>
</html>
And banner.html contains just the following (as an example):
<h2>Subheading</h2>
<script>
document.write('Hello');
</script>
The script is executed, but for some reason it strips out the rest of the HTML in both index.html and banner.html (i.e. it just displays "Hello" and nothing else).
Any help greatly appreciated!
document.write after the page has load writes to the document, and at the same overwrites everything else currently in the document, that's why you end up with only the string "hello".
Just remove the document write :
<h2>Subheading</h2>
<p id="test"></p>
<script>
document.getElementById('test').innerHTML = 'hello';
</script>
that is becuase when banner.html is loaded .. the script inside banner.html get executed, which writes "hello" in your document(the document here is your entire index.html)
one way to understand this is by replacing certain content of banner.html rather than the whole document.
banner.html
<h2>Subheading</h2>
<div id="divID"></div>
<script>
$('#divID').html('hello'); //using jquery .. gets the element with id as divID and replace the HTML
</script>
here i am replacing just the div whose id is "divID" rather than replacing the enrite document
I have a script in an HTML page of the following:
<script id="scriptid" type="text/html">
<div id="insidedivid">
... html code ...
</div>
</script>
I am able to get the HTMLScriptElement using $("#scriptid") but I am not able to get the underlying div object with the id "insidedivid". Whats the way to do it?
It's not possible; the browser does not treat HTML content inside of <script> tags as part of the DOM. When you retrieve the content of the <script> tag with $('#idhere').html(), you're getting a string result.
To answer Troy's question, he's most likely including templates in the <head> of his document so he can ultimately render content dynamically on the browser-side. However, if that is the case, the OP should use a different MIME type than text/html. You should use an unknown MIME type such as text/templates--using text/html confuses what the purpose of the content is.
I'm guessing the reason you're trying to reach into the <script> tag and grab a div is because you've built smaller sub-templates within the single <script> tag. Those smaller templates should rather be placed into their own <script></script> tags rather than contained in one large <script></script> tag pair.
So, instead of:
<script type="text/template" id="big_template">
<div id="sub_template_1">
<span>hello world 1!</span>
</div>
<div id="sub_template_2">
<span>hello world 2!</span>
</div>
</script>
Do this:
<script type="text/template" id="template_1">
<span>hello world 1!</span>
</script>
<script type="text/template" id="template_2">
<span>hello world 2!</span>
</script>
I think it's perfectly valid to have a div inside a script tag (or at
least useful), if a div makes sense to the TYPE you defined for the
script. For example, John Resig uses a script tag with type "text/
html" in his micro-templating solution:
http://ejohn.org/blog/javascript-micro-templating/
In this instance though (and in reply to the original author) you add
an ID to the SCRIPT tag, and refer to that (I don't see why it
wouldn't work with that facebook type instead of html - but you'd
probably want to test it in a few different browsers ;). For the
example you gave, you can get a reference to the DIV by doing:
<script id="scriptid" type="text/html">
<div id="insidedivid">
... html code ...
</div>
</script>
$(function(){
alert($( $( '#scriptid' ).html() ).text() ); //alerts " ... html code ..."
});
The "trick" is to get the HTML of the script tag and turn in into DOM
elements with jQuery - but remember, because you are passing all the
HTML into the jQUery function then you are immediately selecting ALL
of the top level elements. In this case, there is just one DIV - so
you are just selecting that.
Your HTML is invalid. HTML Validator.
If you want to have HTML you can get just like that, use something like this:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<title></title>
<script type="text/javascript" src="//code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var msg1 = $('message1');
// Execute code here
});
</script>
</head>
<body>
<div id="content">Content</div>
<div id="hidden" style="display: none">
<div id="message1">Message 1</div>
<div id="message2">Message 2</div>
</div>
</body>
</html>
If you are making a templating system, you may want to use AJAX instead.