I am looking to have a chunk of html containing a heading which i want to reuse across multiple html pages.
I have tried the EXACT code but it doesn't seem to work. it is displaying the script in HTML rather than actioning it.
index.html:
<html>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<h1>This is a test</h1>
<script>$("#content").load("commonContent.html");</script>
</html>
commonContent.html:
<div id="content"><h2>If this shows my test worked!</h2></div>
Any suggestions would be much appreciated. Please note i am a newbie to javascript!
You need:
To include the jQuery library since your script depends on it
To put your script inside a <script> element
To put an element in the document in which you will load the content (you are trying to use one with id="content" but no such element exists).
I'd recommend using a server side or build time template system instead though. They are more reliable and better food for search engines.
For this type of thing I usually use php like this:
<?php include("youhtmlfile.html"); ?>
It is an advantage because this way you don't have to worry about browser support.
Related
I'm trying to figure out how to get all the elements of html. For example, if I load this google search, I'll see this result:
Looking at the source code for that particular section of the page, I saw this:
<a href="https://www.macworld.com/article/3331839/iphone-2019-rumors-everything-you-need-to-know.html" onmousedown="return rwt(this,'','','','38','AOvVaw07dY5FgPEzcYsd8enm-9gs','','2ahUKEwicoNi4yPjhAhVdCTQIHVxICj4QFjAlegQIABAB','','',event)">
<h3 class="LC20lb">iPhone 2019 rumors: Everything you need to know | Macworld</h3><br><div class="TbwUpd">
<cite class="iUh30">https://www.macworld.com/.../iphone-2019-rumors-everything-you-need-to-know.ht...</cite></div></a>
But if I use document.documentElement.innerHTML, I see this:
<div class="g"><h3 class="r">
<a href="/url?q=https://www.macworld.com/article/3331839/iphone-2019-rumors-everything-you-need-to-know.html&sa=U&ved=0ahUKEwiU__rUy_jhAhWIHzQIHTrGBzIQFghLMAo&usg=AOvVaw2C3PdwxIaeNuukMVSwC-5g">
<b>iPhone 2019</b> rumors: Everything you need to know | Macworld</a>
</h3><div class="s"><div class="hJND5c" style="margin-bottom:2px">
My question: why is there a difference between the source code and the output from document.documentElement.innerHTML?
Also, it looks like this when using JavaScript:
<a href="https://www.macworld.com/article/3331839/iphone-2019-rumors-everything-you-need-to-know.html" onmousedown="return rwt(this,'','','','38','AOvVaw07dY5FgPEzcYsd8enm-9gs','','2ahUKEwicoNi4yPjhAhVdCTQIHVxICj4QFjAlegQIABAB','','',event)">
<h3 class="LC20lb">iPhone 2019 rumors: Everything you need to know | Macworld</h3><br><div class="TbwUpd">
<cite class="iUh30">https://www.macworld.com/.../iphone-2019-rumors-everything-you-need-to-know.ht...</cite></div></a>
I wasn't able to re-produce you problem, in my case source code showed exactly the same as document.documentElement.innerHTML. So, I don't really know why in this particular example you have this particular problem.
Even though, source-code of the page frequently may have nothing to do with document's innerHTML.
innerHTML have at least 2 inaccuracies:
It shows result of JS execution that might modify DOM.
For example, here you have the source code of a sample React App.
<body>
<div id="app"></div>
<script src="main.js"></script>
</body>
And here's the output it produces:
In this case, the source is completely different from the innerHTML since we generate new things with js.
However, it'd also be different if we would modify existing markup with JS & It's probable that this is the case with Google's result page.
innerHTML shows what browser have parsed, not the content that was sent from the server.
For example, if I sent a bad HTML from the server like this:
<head>...</head>
<!DOCTYPE html>
<html lang="en">
<body>...</body>
</html>
Then document.documentElement.innerHTML will nicely output my bad markup like this:
<head>...</head>
<body>...</body>
This one probably doesn't affect Google's page but it also worth considering when you build something on the basis of document's innerHTML.
So, if what you really want is the source code of the page, probably, you just need to fetch it from the server directly & just get text out of the response.
In client-side JS you can do so with fetch API. The only problem is that you might not be able to do so from an origin different from google.com since you might run into CORS policy problem.
From the server-side, you certainly would have a tool to do a GET request. So, you might use something like http.get in NodeJs or file_get_contents() in PHP.
Google's HTML tags are way more complex than what you're looking for, but I assume you want something like this
x = document.querySelectorAll('.g')
x.forEach(function(element) {
console.log(element.outerHTML);
});
To me, it looks like certain part of the page is dynamically generated through script at client end and that this script is stored at server side other than google. Therefore you might have to run through CORS policy problem. So, "document.documentElement.innerHTML" will only show the static elements of the page that was written initially to be shown at client side, leaving the script that generated the other elements dynamically.
The returned HTML or XML fragment is generated based on the current contents of the element, so the markup and formatting of the returned fragment is likely not to match the original page markup.
for more detail
I am given this code which should display an embedded small coupon version of this page https://weedmaps.com/deals#/1118217:
<script type="text/javascript">var coupon_id = 17811;</script>
<script type="text/javascript">var coupon_type = "deliveries";</script>
<script type="text/javascript" src="https://weedmaps.com/embed/coupon.js"></script>
I do not know how to add the JavaScript to the HTML correctly. I have placed the following scripts in the head section. But I don't understand how to have the coupon generate in the div I want it to. I have tried calling the JavaScript function, but I've never worked with JavaScript before. Could someone please help me embed this coupon.
I've taken a look at your script and first of all: it definitely should be placed inside the document and not into the <head> section because coupon.js is writing out html at the placement of the coupon.js script import.
In theory you just need to place the script and it should work but there are some problems:
You need to execute it on a web server - when running as a plain html file the script just tries to find the libraries in your file system which does not work.
It still would not work because it would still try to find some resources at your web-server. In mycase it the script tried to load http://localhost:63342/restpoints/deliveries/17811/deal which will not work
To prove 2. just try https://weedmaps.com/restpoints/deliveries/17811/deal with the correct domain. Then you are receiving correct JSON which is used to fill the coupon pane.
=> Consequently the script you were given has problems if it should be executable from domains different from "weedmaps.com"
Javascript can be between head tag but it advisable to put it below before the body closing tag, to allow your page contents loads first before loading javascript. Just import your javascript. and call out. Hope this was helpful.
<!DOCTYPE html>
<html>
<head>
</head>
var coupon_id = 17811;
The JS indicates it is looking for an element with an id of #weedCouponPane. Do you have this in your html? i.e.
<div id="weedCouponPane"></div>
On my website I have a menu button that goes on every page and also a comments section. Instead of copying and pasting this into every single HTML file I created a JavaScript file that creates all of the HTML via the document.write function. This works fine, but as it is getting more and more lengthy and complicated it is also getting harder and harder to find elements and attributes since they are all squashed in one line.
I want to know if there is a better way to do this because I feel this is not the correct way due to it being so messing and disorganized.
I am just using a JavaScript file. It would look something like this:
document.write("<div id="id"></div>");
but with a lot more HTML.
I would suggest templating with a server side language such as PHP. This will allow you to format your different sections so that they are easily readable. Also it will work even if JavaScript is turned off on the browser.
<html>
<head></head>
<?php require("menu.php"); ?>
<!-- HTML body content -->
<?php require("comments.php"); ?>
</html>
If you want to stick with a client side approach then you can just put your menu and comments into separate html files and use jQuery to load it using
$('#Menu').load('menu.html');
$('#CommentSection').load('comments.html');
You can use jquery
Put your button in its own .html file like button.html with .load() in main html file.
$('#WhereYouWantItID').load('whatfolder/button.html');
This will load the button.html file to a specific target on your page
My question is similar to this one
How to include an HTML page into another HTML page without frame/iframe?
But the answers are not working for me. Objects and iframes create a box with scrollbars, which I don't want, and if I have links to other pages, I would like the whole page to change, not just what's inside the box.
This instruction doesn't work
<!--#include virtual="/footer.html" -->
I want to use only html, because this is how the website has been built and we are not redesigning it. I am only doing this for content modification purposes.
Is it a bad practice to write an html header (or footer) in a javascript file then include the .js in all of my html files?
1st edit
I have about 70 different html static pages.
I want to update contents such as the logo, the menu, the meta description of the web site, the text color, etc. but at the moment, I have to make each of these modifications 70 different times.
I used javascript for the html part of the menu, because the menu worked with javascript anyway, and included the file in all of my html files.
function writeJS(){
var strVar="";
strVar += "<body bgcolor=\"#000000\">";
strVar += "<div class=\"Main_container\">";
...
document.write(strVar);
}
writeJS();
I don't know if it is a good or bad idea to do the same with those tags for example.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org
/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" ...
2nd edit
Although the html/javascript option was viable, we decided to invest a couple of days to go for a wordpress.org site (cheaper and better in the long run).
This instruction doesn't work at all
<!--#include virtual="/footer.html" -->
...probably becaue SSI is not enabled. Presumably you're telling us this because you think it would give you the result you want - implying that part of the question is why didn't it work? What did you do to investigate?
Is it a bad practice to write an html header (or footer) in a javascript file then include the .js in all of my html files?
It's not about bad practice - it won't work - you can inject html from javascript - but you need javascript code to do the injecting. Also this contradicts your earlier statement:
I want to use only html
The code you've provided does not inject html it appends it. The problem with document.write is that it only writes to the end of the document input stream. And if that stream is already closed, it re-opens it and clears the current HTML. There's never a good reason to use document.write(). Consider:
<html>
<div id="header">
<noscript>....</noscript>
</div>
<div id="page_specific_content">
...
</div>
<div id="footer">
<noscript>....</noscript>
</div>
</html>
and...
function addHeader()
{
var el=document.getElementById("header");
if (el) {
el.innerHTML="...";
}
}
But this is still a bad way to write a dynamic website. Even if you don't want to run ASP or PHP or PERL or serverside JS or.... on your production server, it'd make a lot more sense to to dfevelop using a proper CMS or templating system then scrape the HTML to get a static version for publication.
Yes, it is bad practice. Use the right tool for the right job.
For most of the things you mention, you need to use an external stylesheet (bgcolor in 2013?). This will already prevent you from having to change 70 files.
If there's also content you wish to share between pages, the proper way would be to use server-side scripting (such as php) to include it.
Including it client side is messy and will only work partly. You can only load things that go into the DOM (so not your meta information or your Head element's content). Plus your site will be completely disabled when a user does not have javascript enabled (not that common these days, but still).
I guess there could be numerous ways to do this:
Use SSI as described in the solution at How to include an HTML page into another HTML page without frame/iframe?
If you have php or similar scripting languages and feel confortable, you could use it.
Use simple js injection using JQuery or native JS code. See: https://stackoverflow.com/a/676409/2027264
Use IFrames with some CSS to get rid of scrollbars
Use Javascript templates(Underscore, backbone and many others). Also see: What Javascript Template Engines you recommend? and http://en.wikipedia.org/wiki/Javascript_templating
Hope this helps.
I'm fairly sure that include solution only works server side. Did you try the jQuery solution that was provided on that page? It seems to fit your javascript requirement:
If you mean client side then you will have to use JavaScript or frames.
Simple way to start, try jQuery
$("#links").load("/Main_Page #jq-p-Getting-Started li");
Source comment.
The reason I don't want to use ajax to do this is because the part I want to refresh is actually a commenting plugin implemented by other. I just put a snippet of script they provided in my html code and it shows a commenting part under my articles. As it's not a live commenting one, I want to add a refresh button next to it to enable users to just refresh the commenting part to get the latest comments without need for reloading the whole page.
Therefore, I think maybe iframe is an option for me. But the problem is I need to specify the src attribute of iframe. I don't know what value I should use because all I have is just a snippet of script. Can someone give me any idea on this?
By the way, the code snippet is as follows:
<div id="uyan_frame"></div>
<script type="text/javascript" id="UYScript" src="http://v1.uyan.cc/js/iframe.js?UYUserId=1674366" async=""></script>
Just create a html page with the script you talked inside about and use this file in the iframe src attribute.
You can put the snippet above in an html file like this
<!DOCTYPE html>
<html>
<body>
<div id="uyan_frame"></div>
<script type="text/javascript" id="UYScript" src="http://v1.uyan.cc/js/iframe.js?UYUserId=1674366" async=""></script>
</body>
</html>
And then use that file as the src of your iFrame, which you can refresh using javascript.
That said, just because you can do something doesn't mean you should do something. This is a really hacky way of doing what you're trying to do. A few alternative options:
Understand what the script you're using is doing, and work with it. Judging by the name of the script and div in the snippet, it may be creating an iframe to begin with. If thats the case, why not just figure out what that iFrame is called using your browsers debug it and refresh it manually, or modify the script to do so?
Use a live updating framework- This may not be possible for you, I don't know your constraints, but there are plenty of great commenting frameworks out there that do live updates. For instance Disqus comes to mind. Other examples are facebook comments or you could embed a reference to an external site like branch
Use Ajax - I'm a bit unclear on whether this is your script that you're writing, or a 3rd party script. If it is your script, then use the generally accepted methods for doing this type of work, unless you have a really great reason not too. You'll get better support from others, you'll gain more generally applicable experience, and for the most part, best practices gain that name for a reason. People use "ajax" methods for live updating pages because its effective and useful. Frames have become much less common on the web because they're clunky and make it difficult for different parts of the page to interact. If you don't have a great reason not to use the common practice, its usually your best bet.
You could do this :
var iframe = document.getElementById('your_frame_id');
iframe.src = iframe.src;
set the iframe src to its value again, this will cause the frame to refresh, and will work with cross domain frames