I want home.html to load in <div id="content">.
<div id="topBar"> HOME </div>
<div id ="content"> </div>
<script>
function load_home(){
document.getElementById("content").innerHTML='<object type="type/html" data="home.html" ></object>';
}
</script>
This works fine when I use Firefox. When I use Google Chrome, it asks for plug-in. How do I get it working in Google Chrome?
I finally found the answer to my problem. The solution is
function load_home() {
document.getElementById("content").innerHTML='<object type="text/html" data="home.html" ></object>';
}
Fetch API
function load_home (e) {
(e || window.event).preventDefault();
fetch("http://www.yoursite.com/home.html" /*, options */)
.then((response) => response.text())
.then((html) => {
document.getElementById("content").innerHTML = html;
})
.catch((error) => {
console.warn(error);
});
}
XHR API
function load_home (e) {
(e || window.event).preventDefault();
var con = document.getElementById('content')
, xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (e) {
if (xhr.readyState == 4 && xhr.status == 200) {
con.innerHTML = xhr.responseText;
}
}
xhr.open("GET", "http://www.yoursite.com/home.html", true);
xhr.setRequestHeader('Content-type', 'text/html');
xhr.send();
}
based on your constraints you should use ajax and make sure that your javascript is loaded before the markup that calls the load_home() function
Reference - davidwalsh
MDN - Using Fetch
JSFIDDLE demo
You can use the jQuery load function:
<div id="topBar">
HOME
</div>
<div id ="content">
</div>
<script>
$(document).ready( function() {
$("#load_home").on("click", function() {
$("#content").load("content.html");
});
});
</script>
Sorry. Edited for the on click instead of on load.
Fetching HTML the modern Javascript way
This approach makes use of modern Javascript features like async/await and the fetch API. It downloads HTML as text and then feeds it to the innerHTML of your container element.
/**
* #param {String} url - address for the HTML to fetch
* #return {String} the resulting HTML string fragment
*/
async function fetchHtmlAsText(url) {
return await (await fetch(url)).text();
}
// this is your `load_home() function`
async function loadHome() {
const contentDiv = document.getElementById("content");
contentDiv.innerHTML = await fetchHtmlAsText("home.html");
}
The await (await fetch(url)).text() may seem a bit tricky, but it's easy to explain. It has two asynchronous steps and you could rewrite that function like this:
async function fetchHtmlAsText(url) {
const response = await fetch(url);
return await response.text();
}
See the fetch API documentation for more details.
I saw this and thought it looked quite nice so I ran some tests on it.
It may seem like a clean approach, but in terms of performance it is lagging by 50% compared by the time it took to load a page with jQuery load function or using the vanilla javascript approach of XMLHttpRequest which were roughly similar to each other.
I imagine this is because under the hood it gets the page in the exact same fashion but it also has to deal with constructing a whole new HTMLElement object as well.
In summary I suggest using jQuery. The syntax is about as easy to use as it can be and it has a nicely structured call back for you to use. It is also relatively fast. The vanilla approach may be faster by an unnoticeable few milliseconds, but the syntax is confusing. I would only use this in an environment where I didn't have access to jQuery.
Here is the code I used to test - it is fairly rudimentary but the times came back very consistent across multiple tries so I would say precise to around +- 5ms in each case. Tests were run in Chrome from my own home server:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="content"></div>
<script>
/**
* Test harness to find out the best method for dynamically loading a
* html page into your app.
*/
var test_times = {};
var test_page = 'testpage.htm';
var content_div = document.getElementById('content');
// TEST 1 = use jQuery to load in testpage.htm and time it.
/*
function test_()
{
var start = new Date().getTime();
$(content_div).load(test_page, function() {
alert(new Date().getTime() - start);
});
}
// 1044
*/
// TEST 2 = use <object> to load in testpage.htm and time it.
/*
function test_()
{
start = new Date().getTime();
content_div.innerHTML = '<object type="text/html" data="' + test_page +
'" onload="alert(new Date().getTime() - start)"></object>'
}
//1579
*/
// TEST 3 = use httpObject to load in testpage.htm and time it.
function test_()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
content_div.innerHTML = xmlHttp.responseText;
alert(new Date().getTime() - start);
}
};
start = new Date().getTime();
xmlHttp.open("GET", test_page, true); // true for asynchronous
xmlHttp.send(null);
// 1039
}
// Main - run tests
test_();
</script>
</body>
</html>
try
async function load_home(){
content.innerHTML = await (await fetch('home.html')).text();
}
async function load_home() {
let url = 'https://kamil-kielczewski.github.io/fractals/mandelbulb.html'
content.innerHTML = await (await fetch(url)).text();
}
<div id="topBar"> HOME </div>
<div id="content"> </div>
When using
$("#content").load("content.html");
Then remember that you can not "debug" in chrome locally, because XMLHttpRequest cannot load -- This does NOT mean that it does not work, it just means that you need to test your code on same domain aka. your server
You can use the jQuery :
$("#topBar").on("click",function(){
$("#content").load("content.html");
});
$("button").click(function() {
$("#target_div").load("requesting_page_url.html");
});
or
document.getElementById("target_div").innerHTML='<object type="text/html" data="requesting_page_url.html"></object>';
<script>
var insertHtml = function (selector, argHtml) {
$(document).ready(function(){
$(selector).load(argHtml);
});
var targetElem = document.querySelector(selector);
targetElem.innerHTML = html;
};
var sliderHtml="snippets/slider.html";//url of slider html
var items="snippets/menuItems.html";
insertHtml("#main",sliderHtml);
insertHtml("#main2",items);
</script>
this one worked for me when I tried to add a snippet of HTML to my main.html.
Please don't forget to add ajax in your code
pass class or id as a selector and the link to the HTML snippet as argHtml
There is this plugin on github that load content into an element. Here is the repo
https://github.com/abdi0987/ViaJS
load html form a remote page ( where we have CORS access )
parse the result-html for a specific portion of the page
insert that part of the page in a div on current-page
//load page via jquery-ajax
$.ajax({
url: "https://stackoverflow.com/questions/17636528/how-do-i-load-an-html-page-in-a-div-using-javascript",
context: document.body
}).done(function(data) {
//the previous request fails beceaus we dont have CORS on this url.... just for illlustration...
//get a list of DOM-Nodes
var dom_nodes = $($.parseHTML(data));
//find the question-header
var content = dom_nodes.find('#question-header');
//create a new div and set the question-header as it's content
var newEl = document.createElement("div");
$(newEl).html(content.html());
//on our page, insert it in div with id 'inserthere'
$("[id$='inserthere']").append(newEl);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>part-result from other page:</p>
<div id="inserthere"></div>
Use this simple code
<div w3-include-HTML="content.html"></div>
<script>w3.includeHTML();</script>
</body>```
This is usually needed when you want to include header.php or whatever page.
In Javascript it's easy especially if you have HTML page and don't want to use php include function but at all you should write php function and add it as Javascript function in script tag.
In this case you should write it without function followed by name Just. Script rage the function word and start the include header.php
i.e convert the php include function to Javascript function in script tag and place all your content in that included file.
I use jquery, I found it easier
$(function() {
$("#navigation").load("navbar.html");
});
in a separate file and then load javascript file on html page
showhide.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showHide(switchTextDiv, showHideDiv)
{
var std = document.getElementById(switchTextDiv);
var shd = document.getElementById(showHideDiv);
if (shd.style.display == "block")
{
shd.style.display = "none";
std.innerHTML = "<span style=\"display: block; background-color: yellow\">Show</span>";
}
else
{
if (shd.innerHTML.length <= 0)
{
shd.innerHTML = "<object width=\"100%\" height=\"100%\" type=\"text/html\" data=\"showhide_embedded.html\"></object>";
}
shd.style.display = "block";
std.innerHTML = "<span style=\"display: block; background-color: yellow\">Hide</span>";
}
}
</script>
</head>
<body>
<a id="switchTextDiv1" href="javascript:showHide('switchTextDiv1', 'showHideDiv1')">
<span style="display: block; background-color: yellow">Show</span>
</a>
<div id="showHideDiv1" style="display: none; width: 100%; height: 300px"></div>
</body>
</html>
showhide_embedded.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function load()
{
var ts = document.getElementById("theString");
ts.scrollIntoView(true);
}
</script>
</head>
<body onload="load()">
<pre>
some text 1
some text 2
some text 3
some text 4
some text 5
<span id="theString" style="background-color: yellow">some text 6 highlight</span>
some text 7
some text 8
some text 9
</pre>
</body>
</html>
If your html file resides locally then go for iframe instead of the tag. tags do not work cross-browser, and are mostly used for Flash
For ex : <iframe src="home.html" width="100" height="100"/>
I am very new to coding and am trying to create an app for a study. I am having trouble displaying an element on the correct page of my app using cordova and Xcode. Basically, I want to display a clickable phone number at the end of my app and I am having trouble getting the element to show only on that page (and not on every page of the app). I have figured out how to hide the element, but now I can't get it to appear in the right place. Here is my html code:
<script>
function show(shown, hidden) {
document.getElementById(shown).style.display='block';
document.getElementById(hidden).style.display='none';
return false;
}
</script>
</head>
<body>
<!-- HTML Template -->
<body onload="app.initialize()">
<div class="app">
<div id="window">
<div id="question">
</div>
<div id="popup" style="display:none">
Please call any of the below:
Phone System: 800-555-5555
</div>
</body>
</html>
I tried to include the following in my .js file but it did not work:
var $prehashval = "";
function loop()
{
if (location.hash.slice(1)!=$prehashval)
hashChanged();
$prehashval = location.hash.slice(1);
setTimeout("loop()", 100);
}
function hashChanged()
{
var $output;
switch (location.hash.slice(1))
{
case "question":
document.getElementById('question').style.display = "";
document.getElementById('popup').style.display = "none";
break;
case "popup":
document.getElementById('question').style.display = "none";
document.getElementById('popup').style.display = "";
break;
default:
$output = location.hash.slice(1);
}
}
loop();
I also tried adding the following:
$("#popup").hide()
$("#popup").display()
With no luck. Would appreciate any advice! Thank you.
With the help of some friends, I have fixed this problem! I added the following code to the .js file:
if (question.variableName === 'popup') {
$('#popup').show();
Hope this helps someone in the future!
I have a bunch of web pages where I have an identical construct:
<html>
<head>
<script src="sorttable.js"></script>
<noscript>
<meta http-equiv="refresh" content="60">
</noscript>
<script type="text/javascript">
<!--
var sURL = unescape(window.location.pathname);
function doLoad()
{
setTimeout( "parent.frames['header_frame'].document.submitform.submit()", 60*1000 );
}
function refresh()
{
window.location.href = sURL;
}
//-->
</script>
<script type="text/javascript">
<!--
function refresh()
{
window.location.replace( sURL );
}
//-->
</script>
<script type="text/javascript">
<!--
function refresh()
{
window.location.reload( true );
}
//-->
</script>
</head>
<body>
.
.
.
<script type="text/javascript">
window.onload = function() { sorttable.innerSortFunction.apply(document.getElementById("OpenFace-2"), []); doLoad(); }
</script>
</body>
</html>
This works perfectly in every page except for one, where when the onload function runs it cannot find the sorttable code (which is loaded from sorttable.js up at the top). All these pages are part of the same application and are all in the same dir along with the js file. I do no get any errors in the apache log or the js console until that page loads, when I get:
sorttable.innerSortFunction is undefined
I can't see what makes this one page different. Can anyone see what is wrong here, or give me some pointers on how I can debug this further?
The code I pasted in is from the source of the page where it does not work, but it is identical as the pages where it does work.
Looks like on that page the table with id OpenPhace-2 by which you try to sort have no needed class: sortable
The function innerSortFunction of sorttable object will be present only if there is any table with sortable class exists.
I have a very internationalised website, however I need to produce a pop-up specifically for our UK customers.
What I require is:
On page load: Is the user from the UK?
If yes then show div.
Else
Div remains hidden.
You can do this using freegeoip.
Since you mentioned that you want to use plain JavaScript (not jQuery), you should use JSONP to get the country:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<title>UK localisation</title>
</head>
<body>
<div id="myDiv" style="display:none">
<h1>Kittens</h1>
</div>
<script>
function toggleDiv(content) {
console.log(content.country_code);
if(content.country_code === 'GB') //Or GBR, or UK, I'm not sure.
{
document.getElementById('myDiv').style.display = "inline";
}
else
{
alert("You are not from UK, you are from " + content.country_code);
document.getElementById('myDiv').style.display = "none";
}
}
window.onload = function()
{
// create script element
var script = document.createElement('script');
// passing src with callback name
script.src = 'http://freegeoip.net/json/?callback=toggleDiv';
// insert script to document and load content
document.body.appendChild(script);
}
</script>
</body>
</html>
I have included a file named test.php in the file index.php
lets assume index.php is like this
<html>
<head>
</head>
<body>
<h1 id="dash">Index</h1>
<div id='tab.php'>
<?php include('tab.php'); ?>
</div>
</body>
</html>
and tab.php is like this
<html>
<head>
</head>
<body>
<ul>
<li id='date' onClick="change_head(this.id);">Dates</li>
<li id='appoint' onClick="change_head(this.id);">Appointments</li>
<ul>
</body>
</html>
Here what i would like to do is, if the list item date is clicked(list items are actually tabs). The inner html of the h1 tag with id dash should be changed to Dates and if the list item appoint is clicked the inner html of same h1 tag with id dash should change to appointments.
how can i do that ?? i tried the usual javascript way by taking the ids and applying the if condition to change the innerHTML but it was not working..anyone pls help me how to do it
JAVASCRIPT (this is the js i tried to achive it...i added this in index.php)
function change_head(id){
dash = document.getElementById('dash').innerHTML;
if(id == date){
dash = "Date";
}
else if(id == appoint){
dash = "Appointment";
}
else{
dash = "Index";
}
}
You could try using jquery... something like this:
<script type="text/javascript">
$(document).ready(function () {
$("li#date").click(function () {
$("h1#dash").val("Dates");
});
$("li#appoint").click(function () {
$("h1#dash").val("Appointments");
});
});
</script>
Of course, if you had more of these tabs, I would create a single click event handler for all "li" elements and switch on the ID :-)
Assuming you're new to jquery, you'd also have to include the jquery script in your page. Something like:
<script src="/Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
Check out jquery.com to get started.
If you want do it with JavaScript (i.e. without page reloading), so you need use DOM innerHTML.
Something like (if you didn't use jQuery), didn't test this code through, hope you get idea:
var changetext = function(e,t) {
e.innerHTML = t;
},
elemheader = document.getElementById('dash'),
elemdate = document.getElementById('date'),
elemappoint = document.getElementById('appoint');
if (elemdate.addEventListener) {
elemdate.addEventListener('click',changetext(elemheader,'Date'),false);
}
if (elemappoint.addEventListener) {
elemappoint.addEventListener('click',changetext(elemheader,'Appoint'),false);
}