Include html file into another html file - html

Can someone guide me how to include html file with an html file. I have been trying to embed my file within object tags but to no avail.
Thanks!

You can use the iframe tag.
Another option is to used Server Side inclusion using SHTML, this require that the web server support it, see Server Side Includes

You are quite limited in HTML. You can use iframe tag but it's the same type of embedding as embedding of flash in html pages.
OT: It would be quite easy in PHP. Can you use it? Or do you need static web page?

Can you perhaps use Javascript to dynamically load it in?

You can have it loaded via JQuery as shown here: Include another HTML file in a HTML file
a.html:
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function{
$("#includedContent").load("b.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
b.html:
<p> This is my include file </p>

May be this help:
Inside js/utils.js define functions:
function loadFileSync(fileName) {
var req = new XMLHttpRequest();
req.open('GET', fileName, false);
req.send(null);
if (req.status === 200) {
//console.log(req.responseText);
return req.responseText
} else
return "ERROR!!!"
}
function includeFile(fileName) {
document.write(loadFileSync(fileName))
}
And in main html file add this:
<script src="js/utils.js"></script>
<script> includeFile("navigation.html") </script>

Related

How to separate html text file into multiple files?

Very basic question about html.
Because the <body> is too long, I want to divide the file into multiple files. It is not about using iframe etc, but just want to include multiple text files to create <body> of the html file.
Thank you!
You can do it using jQuery:
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#ContentToInclude").load("b.txt or b.html");
});
</script>
</head>
And load it in HTML:
<body>
<div id="ContentToInclude"></div>
</body>
Just change the extension to .php instead of .html. Then you can just put, for example, your whole head inside the file head.php( or head.inc).
The whole thing would look something like this then:
<!DOCTYPE html>
<?php
include 'head.php';
?>
<body>
<!-- stuff in here -->
</body>
<html>
You can obviously split your body up into seperate pieces like this:
<body>
<?php
include 'firstPart.php';
?>
<!-- some other stuff -->
</body>
You can easily break your code in multiple files, Then create one file with .php extension and include them all!
With only HTML it would not be possible you need to add some JavaScript to be able to do so.
Using a data attribute with the Fetch API and some async functions you could do it as follow:
HTML file:
<div data-src="./PATH/filename.html"></div>
This element will receive as HTML content the content of the file specified in its data-src attribute.
Now the JavaScript:
async function getFileContentAsText(file) {
const response = await fetch(file);
const fileContent = await response.text();
return fileContent;
}
async function insertContentsFromFiles() {
const tbl = document.querySelectorAll('[data-src]'); // get elements with the data attribute "data-src"
for (var i=0; i < tbl.length; i++) // loop over the elements contained in tbl
tbl[i].innerHTML = await getFileContentAsText(tbl[i].dataset.src);
}
// dont forget to call the function to insert the files content into the elements
insertContentsFromFiles();
When the insertContentsFromFiles() method will be called it will first retrieve all the elements that have the data attribute data-src then we loop over these elements using their data-src value with the getFileContentAsText() method to affect their innerHTML property as the content of the file specified in the data attribute.
As we are using querySelectorAll() to get the elements with the data-src attribute the above JavaScript code will work for an unlimited amount of elements as long as they have that data attribute.
Note: In its current state the above JavaScript code is not optimized for loading a big amount of files as it process the files to be loaded one by one. If you are interested in solving this issue you may want to use promise.all() and update the insertContentsFromFiles() method to parallelize the files loading by taking advantage of the asynchronous operations.
Warning: If you plan to use elements that are in the loaded files from JavaScript you will have to retrieve them after they have been loaded into the page otherwise they will have an undefined value. To do so you can dispatch an event when a file has been loaded so you can attach specific functionnalities to the page based on the triggered events.

Use project Javascript and CSS files in a Google Apps Script web app?

If I create a simple HTML web app in Google Apps Script, like this:
function doGet() {
return HtmlService.createHtmlOutputFromFile("index.html");
}
and index.html looks like this:
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<div>Test</div>
is it possible to add JS and CSS files as part of the project and include them using script and link tags, or do they have to be inline/hosted elsewhere?
Here is a workaround I have found useful:
Add this function to your server-side Javascript:
function getContent(filename) {
return HtmlService.createTemplateFromFile(filename).getRawContent();
}
Add a second 'html' file to your project that contains only the JS or CSS surrounded by <script> or <style> tags as appropriate.
<!-- myscript.js.html -->
<script>
alert("Script included!");
</script>
Now you can include the script in your main HTML template like this:
<?!= getContent("myscript.js") ?>
This way, you can have your JS and CSS split into as many files as you like and keep them all accessible from within the Apps Script project.
Google provides a similar solution here.
Basically, they suggest you add this function to your .gs file:
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.getContent();
}
and add one or both of these to your .html file:
<?!= include('Stylesheet'); ?>
<?!= include('JavaScript'); ?>
the names in quotes of course referring to separate .html files containing your JS or CSS code with <script> or <style> tags.
You can't have simple js or css files in the project so what you do instead is create html files that contain it, and preferably you place the < script>< /script> or < style> inside those files.
So you might have a file a file named myscript.js.html with the following content:
<script>
alert ("Hello World!");
</script>
Now you put this line in the html where you want the asset to be included
Put this in the html where you want to include the asset:
<?= HtmlService.createHtmlOutputFromFile('myscript.js').getContent() ?>
Notice that the ".html" in the filename is omitted.
If you're going to include a number of assets it might be a good idea to make a helper-function. You can put the following function in your code (gs-file)
function include(filename) {
return HtmlService.createTemplateFromFile(filename).getRawContent();
}
Then the line above can be changed to:
<?!= include('myscript.js') ?>
Finally, you also need to call the evaluate()-method of the HTMLTemplate or else the code inside <?!= ?> in the html file wont be evaluated.
So if you're serving the html file like this for instance:
var html=HtmlService.createTemplateFromFile('repeatDialog');
SpreadsheetApp.getUi().showModalDialog(html, 'foo');
You simply need to change it to:
var html=HtmlService.createTemplateFromFile('repeatDialog').evaluate();
SpreadsheetApp.getUi().showModalDialog(html, 'foo');
If you were using createHtmlOutputFromFile and not createTemplateFromFile before then you should know that evaluate() returns htmlOutput so if you're wondering where to put things like .setWidth() then it's after the evaluate() call.
For now, it is not doable to have your CSS and JS script to be part of your Google Apps Script project. You will have to host it somewhere else and point the URL in your template.
You can directly render a file inside a scriptlet tag.
<?!= HtmlService.createTemplateFromFile("example.js").getRawContent() ?>
Create the example.js.html file in your apps script project. While rendering in the scriptlet tag do not mention the extension ".html"

Offline mobile application - should i be able to read in a localally stored JSON file?

My question is similar to the one here Trying to parse JSON file with jQuery but i don't seem to be able to adapt it.
I want to create an offline mobile app mainly using HTML5, CSS and JavaScript/Jquery
All the files in the app will be cashed I hope when I've it working
I had thought to created a JSON file containing some data about computer labs - eg open hours capasity that type of thing
{ "name":"Boole basement",
"location":"Main Campus",
"staffed":"Yes"}
And then read in the localy stored JSON file - parse it or whatever and then display each object in a new div. Initially I was just trying to get the data into one div. heck if I could get the contents of the JSON file to display I'd be delighted!
My HTML file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>test</title>
<script src="jquery-1.6.2.min.js"></script>
<script>
/* <![CDATA[ */
$(document).ready(function(){
var test =" ";
var filename = "test.json";
$.getJSON(filename, function(json){
$.each(json.labs, function(i, lab){
test = lab.name;
test+=" "+lab.location;
$('#space').append(test);
alert("Hi");
});
});
});
/* ]]> */
</script>
</head>
<body>
<h2>available labs:</h2>
<div id="space">some text</div>
</body>
</html>
PS Is what I've discribed even possible...
What you have described is entirely possible, yes. But your code needs work:
For example, your selector for space is incorrect (it's an ID in your mark-up, but you're using a class selector in your jQuery code).
(EDIT OK, I see you've edited your example code now).

How to call Processing.js function from HTML?

I'm exploring HTML5 and Processing.js.
When the user clicks on an image on my webpage, I'd like to call a function in the Processing.js code. Just calling the function in onclick, as illustrated in this simple example, isn't working:
<html>
<head>
<script language="javascript" src="processing.init.js"></script>
<script language="javascript" src="processing.js"></script>
</head>
<body>
<script type="application/processing">
void restart()
{ /* does something */ }
</script><canvas>
You'll need a browser that supports HTML5 to see this content.
</canvas><br/><br/>
<img src="restart-image.png" onclick="restart()">
</body>
</html>
Any thoughts on how I can call a method in the Processing.js script when an image is clicked? (Maybe I'm making a basic HTML mistake by using img onclick?)
This should work, enclose you image inside the anchor tag <a> image </a>
Use href tag to call the function.
image source
I would start by pulling the javascript for the onclick out of the img tag.
In a separate javascript file you can have:
document.getElementById('restartimage').onclick = function() { Processing.setup(); }
Obviously I put an id attribute on your img tag.
The setup function I noticed on this page:
http://processingjs.org/
The basic idea is that by pulling the onclick into a javascript file it will be easier to code what it should do.
you need to change the script-type to text/javascript or application/javascript first.
then place 'function' before 'restart()' function reducing 'void'.
i have used firefox 3.0.14 on ubuntu 9.04.
You can call processing functions using the Processing js object's getInstanceById function.
For example here is a function:
$(window).resize(function(){
var p=Processing.getInstanceById('processing_canvas_id');
p.resize($("#main").width(),$("#main").height());
});
Where resize is my processing function inside the processing file associated with processing_canvas_id.

Grabbing Google Directions gadget from Ajax call

I am trying to throw together a website using Ajax for the first time, to finally get with the times and figure it out. So far it is nothing but HTML pages and a bit of JS. Using some basic AJAX script I found online, I have the main index.htm which has a title, navigation, and content divs. The Ajax calls grab other content includes (which are just files with text content for the most part) to throw into the content div. For the most part it works, except for when I am trying to add the Google Directions gadget. When I add the script code it gives me to a file and call that file, there is no noticeable output.
Any suggestions on what I am doing wrong or what I'm missing?
If I am understanding you correctly this is an unnecessary use of AJAX. From what it seems like you want to do is load JavaScript via a JavaScript call. This can be accomplished using either method described here. Example:
<script type="text/javascript">
function dhtmlLoadScript(url)
{
var e = document.createElement("script");
e.src = url;
e.type="text/javascript";
document.getElementsByTagName("head")[0].appendChild(e);
}
onload = function()
{
dhtmlLoadScript("dhtml_way.js");
}
</script>
If the above link does not help or I am misunderstanding your question please provide further clarification or some sort of code example.
Following up on your comment
Here is a work around for your gadget, the below code would be on your main page (the one that is initially loaded). Here is my test HTML page:
<html>
<head>
<script type="text/javascript">
var gadget;
function getGadgetAndMove(node)
{
gadget = document.getElementsByTagName("table")[0];
node.appendChild(gadget);
gadget.style.visibility = "visible";
gadget.style.display = "inline-block";
}
</script>
<style>
.ig_reset, .ig_tbl_line { visibility:hidden;}
</style>
</head>
<body>
<div onclick="getGadgetAndMove(this);">Test</div>
</body>
<script src="http://www.gmodules.com/ig/ifr?url=http://hosting.gmodules.com/ig/gadgets/file/114281111391296844949/driving-directions.xml&up_fromLocation=&up_myLocations=1600%20Amphitheatre%20Pkway%2C%20Mountain%20View%2C%20CA&synd=open&w=320&h=55&title=Directions+by+Google+Maps&brand=light&lang=en&country=US&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>
</html>
If you need further explanation please let me know.
I believe I know what you want to accomplish, because I ran into the same problem. And I found a solution. So I would say that no it is not an improper use of ajax, because you could run into this in some circumstances.
Put the directions gadget not directly in the page content that is being loaded via ajax, but in a separate file such as "directionsgadget.html" (insert the script tag for the gadget in this file).
Then use an iframe with src="/path/to/directionsgadget.html" in your ajax loaded content.
The gadget should get loaded this way.
If you want the gadget centered within the iframe, you can wrap the script tag in directionsgadget.html in a div with a set width and style="margin:0px auto". That will center the gadget.
Here is an example:
Your main page is "index.html", and contains a div that will contain ajax loaded content:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'ajaxcontent.html',
success: function(returndata){ $('#ajaxcontent').html(returndata); }
});
});
</script>
</head>
<body>
<div id="ajaxcontent"></div>
</body>
</html>
Then you have a file with the content that is to be loaded via ajax, and this has among other things a google gadget. Were not going to put the gadget directly here, but were going to put it in a separate file and point to it with an iframe. Let's call this first file ajaxcontent.html, as indicated in the ajax call in the head section of the first file:
<span>Here is some content that will be loaded onto the main page via ajax.</span><br />
<span>Among other things, there is a google directions gadget that will be loaded.</span>
<div id="getdirections" style="margin:0px auto;">
<iframe style="width:365px;height:216px;" src="directions.html"></iframe>
</div>
Now we will put the script for the google gadget itself in a separate file "directions.html" (as indicated in the src of the iframe above), and in order for the rendered gadget to be centered we are going to wrap the script tag within a div just so:
<div style="width:336px;height:116px;margin:0px auto;">
<script type="text/javascript" src="http://www.gmodules.com/ig/ifr?url=http://hosting.gmodules.com/ig/gadgets/file/114281111391296844949/driving-directions.xml&up_fromLocation=&up_myLocations=_a_bunch_of_information_with_personal_list_of_locations_&synd=open&w=320&h=55&title=Street+directions+by+Google+Maps&brand=light&lang=it&country=ALL&border=http%3A%2F%2Fwww.gmodules.com%2Fig%2Fimages%2F&output=js"></script>
</div>
I hope this example was clear enough!