How to include a html file into another? - javascript

I am relatively new so I may not have done them right but I have tried them. The closest I got is the code I am including. It was work for awhile but the modals wouldn't "fire". I tried to remedy that and lost my inclusion. So here goes.
HTML
<!--============================================-->
<!-- End of Main Program, Modals Follow -->
<!--============================================-->
<section id="activeModal">
<!--> placeholder for every modal in this project </!-->
<!--> each modal is stored in a separate file (modals.html) </!-->
<!--> main.js builds an include with a js script, appends it here, and it executes (hopefully) </!-->
</section><!-- /activeModal -->
JS
// event listener for modals
$("button").on('click', function() {
for ( i=0; i<this.attributes.length ;i++ ) { // this - identifies the modal sought
if ( this.attributes[i].name === "data-target" ) {
var target = this.attributes[i].value; // get the modal to "fire" (data-target attribute)
};
};
modalId = "modals/"+target.substring(1, target.length)+".html"; // strip the '#' from target
$("#activeModal").empty(); // remove any previous modal information
includeHTML = '<!--#include virtual="'+modalId+'" -->'; // include via ssi (server side include)
$("#activeModal").append(includeHTML); // append the 'import' html
$(target).modal("show"); // show the modal
});
I am expecting the html for any of about 20 modals to appear in the activeModal <section> of index.html. Then, I have the problem of making them "fire".

Based on this line, it looks like you are trying to use server-side includes on the client-side when a button is clicked.
includeHTML = '<!--#include virtual="'+modalId+'" -->'; // include via ssi (server side include)
This is quite simply impossible.
You can't trigger a server-side include with client-side code. Server-side includes must be made before the response is sent to the client. To get more data from the server, you will have to initiate another request, perhaps via AJAX.

var stackoverflowResponse = document.createElement("div");
stackoverflowResponse.innerHTML = "Look in the console for the answear";
document.body.replacewith(stackoverflowResponse);

You could try changing the extension of your index.html to .shtml, and then using Server Side Includes to include the content of another file.
<!--#include file="included.html" -->
When I did this, I also believe I had to update the .htaccess file to recognize the .shtml as an index file:
AddType text/html .shtml
AddHandler server-parsed .shtml
AddHandler server-parsed .shtml .html
AddHandler server-parsed .shtml .htm

Well you can try out something like this using jquery:
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includedContent").load("xyz.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>

Related

How to use external html file in current html code

I am trying to load an external HTML page (common navigation) into my current HTML page. I tried the load function but it is deprecated. Can you tell me another way to include it? I am not using any server.
Here's my code
<!DOCTYPE html>
<html>
<head>
<script src="ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#content').load(" nav.html ");
});
</script>
</head>
<body>
<div id="content "></div>
</body>
</html>
Try this
<script>
function loadPage(href) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", href, false);
xmlhttp.send();
return xmlhttp.responseText;
};
document.getElementById('content').innerHTML =
loadPage('your_html_file.html');
</script>
<div id="content">
</div>
Take both file pages in same directory then you can use simple button on link to use external file. for example
<button> External file </button>
Button is your choice it's just example for understanding you can simple use html link.
You should use the SSI-function.
There is several ways but this can solve your problem.
<!--#include virtual="PathToYourFile/YourFile.html" -->
This can be inserted into a <div> for further styling in CSS.
REMEMBER! Due to some limitations in html-doctypes you cannot inlude a .html-file into an .html-file. You have to use another format as .shtml where you can inlude your .html-files. You can include .html into your .shtmlfile. This was also what .shtml was originally created for.
This is because it is part of the XHTML (Dynamic XML HTML)...
To change a file
Your approach on the HTML is correct and also your JS. I include a lot of html-files containing texts there.
My approach is that when a page is loaded some text will be loaded with the <!--#include virtual="" --> inside a <div>. Below JS is used to change the content in the <div>. As Daniel Beck stated below: "...at least in Apache the server needs to be configured to check particular file extensions...".
You configure your file in your .htaccess-file. But ONLY do this if you know what you are doing.
Some (newer?) servers have a default setup of which you don't need to alter the .htaccess-file if you want to be able to include .html-files. At least you are able to include .html-files into .shtml-files.
I have included a Mimetype converter which tells the browser how it should read the file. For txt/html I have told the script that it should use the character encoding ISO-8859-1. Others as UTF-8 could also be used. This depends on your and your receivers native language.
Take into consideration to use the e.preventDefault();. With this i tells the browser NOT to see this as navigation link and will therefore only load the content in the <div>.
$(function() {
$('#ButtonsID').click(function(e) {
$('.DivClass').load('PathToFile/File.shtml');
e.preventDefault();
});
});
$.ajaxSetup({
'beforeSend': function(xhr) {
xhr.overrideMimeType('text/html; charset=ISO-8859-1');
}
});

How to go up one level in javascript (when using Ajax.open) [duplicate]

So I'm running this javascript, and everything works fine, except the paths to the background image. It works on my local ASP.NET Dev environment, but it does NOT work when deployed to a server in a virtual directory.
This is in an external .js file, folder structure is
Site/Content/style.css
Site/Scripts/myjsfile.js
Site/Images/filters_expand.jpg
Site/Images/filters_colapse.jpg
then this is where the js file is included from
Site/Views/ProductList/Index.aspx
$("#toggle").click(function() {
if (left.width() > 0) {
AnimateNav(left, right, 0);
$(this).css("background", "url('../Images/filters_expand.jpg')");
}
else {
AnimateNav(left, right, 170);
$(this).css("background", "url('../Images/filters_collapse.jpg')");
}
});
I've tried using '/Images/filters_collapse.jpg' and that doesn't work either; however, it seems to work on the server if I use '../../Images/filters_collapse.jpg'.
Basically, I want have the same functionallity as the ASP.NET tilda -- ~.
update
Are paths in external .js files relative to the Page they are included in, or the actual location of the .js file?
JavaScript file paths
When in script, paths are relative to displayed page
to make things easier you can print out a simple js declaration like this and using this variable all across your scripts:
Solution, which was employed on StackOverflow around Feb 2010:
<script type="text/javascript">
var imagePath = 'http://sstatic.net/so/img/';
</script>
If you were visiting this page around 2010 you could just have a look at StackOverflow's html source, you could find this badass one-liner [formatted to 3 lines :) ] in the <head /> section
get the location of your javascript file during run time using jQuery by parsing the DOM for the 'src' attribute that referred it:
var jsFileLocation = $('script[src*=example]').attr('src'); // the js file path
jsFileLocation = jsFileLocation.replace('example.js', ''); // the js folder path
(assuming your javascript file is named 'example.js')
A proper solution is using a css class instead of writing src in js file.
For example instead of using:
$(this).css("background", "url('../Images/filters_collapse.jpg')");
use:
$(this).addClass("xxx");
and in a css file that is loaded in the page write:
.xxx {
background-image:url('../Images/filters_collapse.jpg');
}
Good question.
When in a CSS file, URLs will be relative to the CSS file.
When writing properties using JavaScript, URLs should always be relative to the page (the main resource requested).
There is no tilde functionality built-in in JS that I know of. The usual way would be to define a JavaScript variable specifying the base path:
<script type="text/javascript">
directory_root = "http://www.example.com/resources";
</script>
and to reference that root whenever you assign URLs dynamically.
For the MVC4 app I am working on, I put a script element in _Layout.cshtml and created a global variable for the path required, like so:
<body>
<script>
var templatesPath = "#Url.Content("~/Templates/")";
</script>
<div class="page">
<div id="header">
<span id="title">
</span>
</div>
<div id="main">
#RenderBody()
</div>
<div id="footer">
<span></span>
</div>
</div>
I used pekka's pattern.
I think yet another pattern.
<script src="<% = Url.Content("~/Site/Scripts/myjsfile.js") %>?root=<% = Page.ResolveUrl("~/Site/images") %>">
and parsed querystring in myjsfile.js.
Plugins | jQuery Plugins
Please use the following syntax to enjoy the luxury of asp.net tilda ("~") in javascript
<script src=<%=Page.ResolveUrl("~/MasterPages/assets/js/jquery.js")%>></script>
I found this to work for me.
<script> document.write(unescape('%3Cscript src="' + window.location.protocol + "//" +
window.location.host + "/" + 'js/general.js?ver=2"%3E%3C/script%3E'))</script>
between script tags of course... (I'm not sure why the script tags didn't show up in this post)...
You need to add runat="server" and and to assign an ID for it, then specify the absolute path like this:
<script type="text/javascript" runat="server" id="myID" src="~/js/jquery.jqGrid.js"></script>]
From the codebehind, you can change the src programatically using the ID.
This works well in ASP.NET webforms.
Change the script to
<img src="' + imagePath + 'chevron-large-right-grey.gif" alt="'.....
I have a master page for each directory level and this is in the Page_Init event
Dim vPath As String = ResolveUrl("~/Images/")
Dim SB As New StringBuilder
SB.Append("var imagePath = '" & vPath & "'; ")
ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "LoadImagePath", SB.ToString, True)
Now regardless of whether the application is run locally or deployed you get the correct full path
http://localhost:57387/Images/chevron-large-left-blue.png

Play Framework template that is actually a JS file

I'd like to have a Play template that is a JS file (as opposed to having <script> tags inside an HTML template). The reason for this is so that the script can be cached. However, I need to create a differences in the script depending on where it's included and hoped to do this with Play's template system. I can already do so if I use embedded scripts, but those can't be cached.
I found an existing question that also asks the same thing, but the answer is totally different (different goals).
That's easy, just... create view with .js extension, i.e.: views/myDynamicScript.scala.js:
#(message: String)
alert('#message');
//Rest of your javascript...
So you can render it with Scala action as:
def myDynamicScript = Action {
Ok(views.js.myDynamicScript.render(Hello Scala!")).as("text/javascript utf-8")
}
or with Java action:
public static Result myDynamicScript() {
return ok(views.js.myDynamicScript.render("Hello Java!"));
}
Create the route to you action (probably you'll want to add some params to it):
GET /my-dynamic-script.js controllers.Application.myDynamicScript()
So you can include it in HTML templite, just like:
<script type='text/javascript' src='#routes.Application.myDynamicScript()'></script>
Optionally:
You can also render the script into your HTML doc, ie by placing this in your <head>...</head> section:
<script type='text/javascript'>
#Html(views.js.myDynamicScript.render("Find me in the head section of HTML doc!").toString())
</script>
Edit: #See also samples for other templates types

jQuery's include method doesn't work

As my website has only one page, and the index.html was getting really long and impossible to read. So I decided to put each section in a different HTML file and use jQuery to included it.
I used jQuery's include in the way as it has been mentioned here to include a external HTML file but apparently it doesn't work for my website. I really don't know what is the problem.
Here is the link of my workspace.
Here is what I am doing in index.html file to include other sections
<script src="./js/jquery-1.11.1.min"></script>
<script>
$(function() {
$("#includedContent").load("./page1.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page2.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page3.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page4.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page5.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page6.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page7.html");
});
</script>
I also used this method to make sure the file is accessible and everything was fine. So the problem is not the accessibility of the files
You are overwriting the contents of #includedContent seven times (see documentation of jQuery.load). With AJAX, there is no guarantee which request will complete first so you will end up with random page content inside the container.
The solution is to create containers for each page and load each page inside its dedicated container, something like this:
<div id="includedContent">
<div class="page1"></div>
<div class="page2"></div>
<div class="page3"></div>
</div>
$(document).ready(function() {
$("#includedContent .page1").load("page1.html");
$("#includedContent .page2").load("page2.html");
$("#includedContent .page3").load("page3.html");
});
NB: Having said all that, I do not understand how AJAX solves the problem of the page being too long/impossible to read.
There are several things that look odd to me:
all your load functions run at document ready, which is weird while having all the same target. load replaces (not adds) the content of the selected element with what is being loaded, you probably are trying to add all the html contents, but your current setup would actually just load page7.html into #includedContent
the paths look strange to me, i guess ./ may cause errors, try to leave out ./ everywhere.
rather than loading an entire html page, you might just want to load a piece of that file (i dont know how pageX.html looks), for example you would not want to load the <html> node entirely, rather the content only: .load('page1.html #content')
are you including jquery correctly? there is no .js in your inclusion

Prepare jquery before jquery and page load

I have recently discovered the new trend of including all .js script at the end of the page.
From what i have read so far seems pretty ok and doable with an exception.
The way I am working is using a template like:
<html>
<head>
<!-- tags, css's -->
</head>
<body>
<!-- header -->
<div id="wrapper">
<?php
include('pages/'.$page.'.php');
?>
</div>
<!-- footer -->
<!-- include all .js -->
</body>
</html>
Now, if I want to use this example on my page http://www.bootply.com/71401 , I would have to add the folowing code under my jquery inclusion.
$('.thumbnail').click(function(){
$('.modal-body').empty();
var title = $(this).parent('a').attr("title");
$('.modal-title').html(title);
$($(this).parents('div').html()).appendTo('.modal-body');
$('#myModal').modal({show:true});
});
But that would mean I either use that in every page - even if I do not have use for it, either generate it with php in the $page.'php' file and echoing it in the template file, after the js inclusion.
I am sure though, better methods exist and I don't want to start off by using a maybe compromised one.
Thanks!
Please avoid using inline scripts as they are not good maintainable and prevent the browser from caching them. Swap your inline scripts in external files.
Fore example you could put all your JavaScript in one file an check the presence of a specific element before initialize the whole code. E.g.:
$(document).ready(function(){
if($('.thumbnail').length) {
// your thumbnail code
}
});
A better way to execute "page specific" JavaScript is to work with a modular library like requirejs. You can modularize your scripts depending on their functionality (like thumbnails.js, gallery.js etc.) and then load the necessary script(s) depending e.g. on the existence of an element:
if($('.thumbnail').length) {
require(['ThumbnailScript'], function(ThumbnailScript){
ThumbnailScript.init();
});
}
The best way you can go is create a separate file for this code.
Let's name it app.js. Now you can include it under the jQuery inclusion.
<script type="text/javascript" src="app.js"></script>
This will prevent code repeat.
One more thing, pull all the code in $(document).ready(). Here is an example. So your app.js file will look like this:
$(document).ready(function(){
$('.thumbnail').click(function(){
$('.modal-body').empty();
var title = $(this).parent('a').attr("title");
$('.modal-title').html(title);
$($(this).parents('div').html()).appendTo('.modal-body');
$('#myModal').modal({show:true});
});
})

Categories

Resources