Including <div></div> in a library - javascript

I have a few "div" sections that are called by my Javascript function using document.getElementById('ID_NAME').style.display='block'.
My question, is there a way to include these "div's" in a .js, .css or another type of library sourced from my header?
If I copy and paste the div code directly into the head it works fine, however, when I try to include it in my .js or .css libraries it wont execute.
CODE
<script type="text/javascript>
function myFunction() {
var a = window.location.href;
var b = "http://www.myblog.com/";
if (a == b) {
setTimeout(function(){
document.getElementById('EXAMPLE1').style.display='block';}, 3000);}}
window.onload = myFunction();
</script>
<div id="EXAMPLE1" class="offer_content">
<embed src="http://www.domain.com/" width="100%"
height="100%">
</div>
I know there has to be a way to insert "div" code into a library. I need some of my clients to "src" it into their own websites easily.
Much appreciated Stack community!
Jon

In another separate JS file, divs.js:
divs.js
function changeDiv(){
document.getElementById('EXAMPLE1').style.display='block';
}
index.html
<script src="divs.js"></script>
<script type="text/javascript">
function myFunction() {
var a = window.location.href;
var b = "http://www.myblog.com/";
if (a == b) {
setTimeout(changeDiv, 3000);
}
window.onload = myFunction();
</script>
<div id="EXAMPLE1" class="offer_content">
<embed src="http://www.domain.com/" width="100%"
height="100%">
</div>
Also, there seems to be syntax errors in your code. Try to run this file with a JS console (use something like "Firebug") for debugging purposes.

I wanted to post that I finally worked this problem out. While my Javascript library wouldn't support code with some code in it, I was able to convert everything with DOM.
OLD CODE::
<div id="EXAMPLE1" class="offer_content">
<embed src="http://www.domain.com/" width="100%"
height="100%">
</div>
NEW CODE::
var embed = document.createElement('embed');
embed.setAttribute("src", "http://www.domain.com/");
embed.setAttribute("width", "100%");
embed.setAttribute("height", "100%");
var content = document.createElement('div');
content.id = 'EXAMPLE1';
content.className = 'offer_content';
content.appendChild(embed);
document.getElementsByTagName('body')[0].appendChild(content);

Related

How to render HTML file using JavaScript [duplicate]

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"/>

iframe onload with src not working in IE11

I have a JavaScript program that gets the last modified date of a txt file. The code works fine in Firefox but for some reason, it does nothing in IE11. My code is listed below.
JavaScript code:
function getLastMod(){
var myFrm = document.getElementById('myIframe');
var lastMod = new Date(myFrm.contentWindow.document.lastModified);
var getSpan = document.getElementById('LastModified');
getSpan.innerHTML += "<font color=red> (File Last Updated: " + lastMod.toLocaleString() + ")</font>";
}
HTML code:
<span id="LastModified"></span>
<iframe id="myIframe" onload="getLastMod()" src="date.txt" style="display:none;"></iframe>
I had a similar issue when I tried to define the event in the tag. I had better results assigning the event from within javascript.
<script type="text/javascript">
document.getElementById('myIframe').onload = function() {
getLastMod();
}
</script>

CDATA Issue Within Magento Rotator

So I'm currently developing a Magento Website. I set up a rotator using the code found here:
http://www.magentocommerce.com/wiki/4_-_themes_and_template_customization/cms_and_home_page/javascript_banner_rotator_for_home_page
If I put the code into the homepage it works as it's supposed to. However if I put the code within a static block CDATA forces itself into the code, breaking it. I'm unable to remove the CDATA as it keeps replacing itself. Code Below:
<script type="text/javascript">// <![CDATA[
var imgs1 = new Array("{{media url="wysiwyg/rotator-1-1.jpg"}}","{{media url="wysiwyg/rotator-1-2.jpg"}}","{{media url="wysiwyg/rotator-1-3.jpg"}}");
var lnks1 = new Array("http://www.example.com/","http://www.example.com/","http://www.example.com/");
var alt1 = new Array("That Looks Nice","That Looks Nice","That Looks Nice");
var currentAd1 = 0;
var imgCt1 = 3;
function cycle1() {
if (currentAd1 == imgCt1) {
currentAd1 = 0;
}
var banner1 = document.getElementById('adBanner1');
var link1 = document.getElementById('adLink1');
banner1.src=imgs1[currentAd1]
banner1.alt=alt1[currentAd1]
document.getElementById('adLink1').href=lnks1[currentAd1]
currentAd1++;
}
window.setInterval("cycle1()",4000);
// ]]></script>
<p><a id="adLink1" target="_top"> <img id="adBanner1" src="{{media url="wysiwyg/rotator-1-1.jpg"}}" alt="" width="235" height="250" border="0" /></a></p>
Any help would be appreciated.
You are commenting the javascript ending </script> tag, try putting </script> after the line CDATA ends.
Not sure about this, but worth a try.

html: print() embed file

I am showing a pdf inside a html using:
<embed id="print" src="file.pdf" type="application/pdf" width="100%" height="100%">
I would like to create a button that prints that file.
I thought it would be something like this; but it isn't working.
<button onClick="javascript:document.getElementById('print').print();">
Anybody an idea how I can call the print function on an embedded file?
<script type="text/javascript">
function printPDF(pdfUrl)
{
var w = window.open(pdfUrl);
w.print();
}
</script>
You can call this function printPDF("http://mywebsite.com/myfile.pdf")

Javascript Syntax Error - I'm a complete noob and can't see it

I'm returning a syntax error on line 9 (screenshot of IDE: http://dl.dropbox.com/u/2578642/Error.png).
I'm complete noob and can't see the error, anyway, here's the code:
<input type = "image" id = "myImage" src = "One.jpg" height ="130" width="173" border="0" Alt="Submit Form" onclick="var fileref=document.createElement('script');fileref.setAttribute('type','text/javascript'); fileref.setAttribute('src', 'http://MYCONTENTLOCKER.com/guid?:1234567890'); showMessage(); setTimeout(changeImage, 30000)">
<br>
<span id = "message" style="display:none">You have completed this part!</span>
<script type = "text/javascript">
var count = 0;
function showMessage () {
if (count > 0) { // line 9
document.getElementById("message").style.display="block";
}
count ++;
}
function changeImage() {
document.getElementById("myImage").src = "Two.jpg"
}
</script>
Thanks for any help!
The code you posted is syntactically fine. I highly recommend you look into the script that you're "dynamically" loading through your inline onclick event handler.
Your JavaScript code looks fine, and the only thing I see that could be causing an issue is the space before and after the = in the HTML attributes.
<script type = "text/javascript">
Should be:
<script type="text/javascript">
So, your code should look like this (I also suggest indenting your code. Makes it easier to read):
<input type="image" id="myImage" src="One.jpg" height="130" width="173" border="0" Alt="Submit Form" onclick="var fileref=document.createElement('script');fileref.setAttribute('type','text/javascript'); fileref.setAttribute('src', 'http://MYCONTENTLOCKER.com/guid?:1234567890'); showMessage(); setTimeout(changeImage, 30000)">
<br>
<span id="message" style="display:none">You have completed this part!</span>
<script type="text/javascript">
var count = 0;
function showMessage () {
if (count > 0) {
document.getElementById("message").style.display="block";
}
count++;
}
function changeImage() {
document.getElementById("myImage").src = "Two.jpg"
}
</script>
I'm not sure if that's the problem, but that's all I could think of.
Just realized that was your whole code. Would you please declare a valid HTML file? The highlighted this should've been a dead giveaway.
Well, it seems to work fine for me.
That said, the only thing I can possibly imagine being wrong is the > on that line is somehow getting escaped as an HTML entity before the page is served. Have you checked that the output of "view source" is indeed the same exact code you wrote?
Technically script elements and other elements with non-CDATA content containing "special" characters should have the content enclosed in a CDATA section. If your HTML code gets run through an XML parser at some point, it will choke on characters like <,>, and &.
With the CDATA section in the script, and the markup written as proper XHTML, the code would look something like this:
<html><head></head><body>
<input type="image" id="myImage" src="One.jpg" height="130" width="173" border="0" Alt="Submit Form" onclick="imageClick()" />
<br />
<span id="message" style="display:none">You have completed this part!</span>
<script type="text/javascript">
/* <![CDATA[ */
var count = 0;
function showMessage () {
if (count++ > 0) {
document.getElementById("message").style.display="block";
}
}
function changeImage() {
document.getElementById("myImage").src = "Two.jpg"
}
function imageClick() {
var fileref = document.createElement('script');
fileref.setAttribute('type','text/javascript');
fileref.setAttribute('src', 'http://MYCONTENTLOCKER.com/guid?:1234567890');
showMessage();
setTimeout(changeImage, 30000);
}
/* ]]> */
</script>
</body></html>
Update: OK, I just realized that you're getting the error in your IDE, not necessarily in the browser. I don't know if the IDE is complaining about the unescaped triangle bracket or not, but i suspect it might be. I don't know if it's smart enough to acknowledge the CDATA section though. I'm curious if this will appease it. What IDE is that, anyway?

Categories

Resources