How to reuse HTML code across multiple pages? [duplicate] - html

I have several pages on a website that use the same header for each page. I was wondering if there was some way to simply reference a file with the html for the header sort of like in this pseudo code:
<!-- Main Page -->
<body>
<html_import_element src = "myheadertemplate.html">
<body>
Then in a separate file:
<!-- my header template html -->
<div>
<h1>This is my header</h1>
<div id = "navbar">
<div class = "Tab">Home</div>
<div class = "Tab">Contact</div>
</div>
</div>
This way I could write the header html once and just import it in each of my pages where I need it by writing one simple tag. Is this possible? Can I do this with XML?

You could do it in this fashion below.
<head>
<link rel="import" href="myheadertemplate.html">
</head>
where you could have your myheadertemplate.html
<div>
<h1>This is my header</h1>
<div id = "navbar">
<div class = "Tab">Home</div>
<div class = "Tab">Contact</div>
</div>
</div>
You can then use it with JS below
var content = document.querySelector('link[rel="import"]').import;

So, after a long time I actually found a way to do this using AJAX. HTML Imports are a great solution, but the support across browsers is severely lacking as of 04/2017, so I came up with a better solution. Here's my source code:
function HTMLImporter() {}
HTMLImporter.import = function (url) {
var error, http_request, load, script;
script =
document.currentScript || document.scripts[document.scripts.length - 1];
load = function (event) {
var attribute, index, index1, new_script, old_script, scripts, wrapper;
wrapper = document.createElement("div");
wrapper.innerHTML = this.responseText;
scripts = wrapper.getElementsByTagName("SCRIPT");
for (index = scripts.length - 1; index > -1; --index) {
old_script = scripts[index];
new_script = document.createElement("script");
new_script.innerHTML = old_script.innerHTML;
for (index1 = old_script.attributes.length - 1; index1 > -1; --index1) {
attribute = old_script.attributes[index1];
new_script.setAttribute(attribute.name, attribute.value);
}
old_script.parentNode.replaceChild(new_script, old_script);
}
while (wrapper.firstChild) {
script.parentNode.insertBefore(
wrapper.removeChild(wrapper.firstChild),
script
);
}
script.parentNode.removeChild(script);
this.removeEventListener("error", error);
this.removeEventListener("load", load);
};
error = function (event) {
this.removeEventListener("error", error);
this.removeEventListener("load", load);
alert("there was an error!");
};
http_request = new XMLHttpRequest();
http_request.addEventListener("error", error);
http_request.addEventListener("load", load);
http_request.open("GET", url);
http_request.send();
};
Now when I want to import HTML into another document, all I have to do is add a script tag like this:
<script>HTMLImporter.import("my-template.html");</script>
My function will actually replace the script tag used to call the import with the contents of my-template.html and it will execute any scripts found in the template. No special format is required for the template, just write the HTML you want to appear in your code.

As far as I know it's not possible. You can load the header as a webpage in a iframe element though. In the past webpages were built with frame elements to load seperate parts of a webpage, this is not recommended and support in current browsers is due to legacy.
In most cases this is done with server side languages like php with as example include("header.php");.

Related

One page html static mutlilanguage

I have a school assignment to create a one page html static.
I want to have some buttons to change the language but I don't want any addition like "index.html/en/" or "index.html?lang=en". I prefer to have it with CSS only but I don't know whether it is possible or not.
In short I just want a simply bilingual "index.html" and have buttons to change the content text.
I am new in html scripting so I'm looking for some sample code or some detailed tutorial will be help.
I suggest using JS/jQuery for that:
Have language mapping for each element that will be translated:
// Translations object:
var translations = {
'en': {
'home': 'Home',
'back': 'Back'
/* ... */
},
'lt': {
'home': 'Pradžia',
'back': 'Atgal'
/* ... */
}
};
// wait for all DOM elements to load
$(document).ready(function() {
// when button is clicked
$('.lang-btn').click(function() {
// take translations subset
var lang = translations[$(this).data('lang')];
// for each element that has "data-key" attribute
$('[data-key]').each(function() {
// change it's content to other language
$(this).text(lang[$(this).data('key')]);
})
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-page">
Language:
<button class="lang-btn" data-lang="en">En</button>
<button class="lang-btn" data-lang="lt">Lt</button>
<hr/>
Home
<button data-key="back">Back</button>
</div>
This code is not checking if there is such translation or not. You can improve this algo with fallback to English.
For SEO reasons I'd prefer to use /en/. Use a .htaccess file with mod_rewrite.
See here Create beautiful url’s with mod_rewrite
If it is just one page, so I assume the contain is not much. Try something simpler like:
function en() {
document.getElementById("content").innerHTML = "Example";
}
function de() {
document.getElementById("content").innerHTML = "Beispiel";
}
<div id="content">sample</div>
<button onclick="en()">English</button>
<button onclick="de()">German</button>

How to customize tumblr 404 URL not found page

It seems Tumblr does not provide a div tag to customize the look and feel of the 'url not found' page.
Is there any way other way to customize the 404 (URL NOT FOUND) Page?
Edit: this method only works on tumblogs that don't have pages.
Ask, Submit, and other pages created in the Customize section will be detected as "not found" with this code.
Description
Tumblr uses the normal {block:Posts} loop for static pages but without assigning any variables like {PostID}. If we use a class like post{PostID}, on 404 pages all static pages we'll see a .post element, whereas on posts the elements will be something like .post125678
Example
{block:Posts}
<div class="post{PostID}">
{block:Photo}all your blocks here{/block:Photo}
</div>
{/block:Posts}
Using javascript:
var is404 = document.getElementsByClass('post').length;
Using CSS:
.post {
/*this is a 404 page, customize it*/
}
Cool javascript-less example
{block:Posts}
<div class="post{PostID}">
{block:Photo}all your blocks here{/block:Photo}
</div>
{/block:Posts}
<div class="fill-me"></div>
In CSS:
.post { /*Hide Tumblr's 404 message*/
display: none;
}
.post + .fill-me:before { /*use your message and style*/
content: 'This page was not found!';
font-size: 2em;
}
Edit: Possible fixes
To fix this method, we should find a {tag} that is only shown on pages but not on 404 pages.
{ShortURL}, if it weren't buggy, could be used since in theory 404 pages shouldn't have a ShortURL.
I also tried {Permalink} but it behaves like {PostID} in this case.
Sadly there isn't an official way to do this.
However, if your using javascript / jQuery, you could sniff for the following text:
The URL you requested could not be found
Example jQuery code:
$(document).ready(function() {
$("p:contains(The URL you requested could not be found.)").html('YOUR TEXT HERE');
});
I would be more incline to add a class to the parent / body element so you can style the whole page differently.
Hope that helps.
This worked for me
<script type="text/javascript">
/* Works for me */
var text_posts = document.getElementsByClassName("regular");
var text_404 = "The URL you requested could not be found.";
var title_404 = "Not Found";
if(text_posts.length == 1){
var bodyNode = text_posts[0].lastChild;
if(bodyNode.previousSibling.textContent == text_404) {
// titleNode.innerHTML = "<a href='/'>Not Found</a>";
var blog_loc = "http://" + document.domain + "/";
var query = window.location.href.slice(blog_loc.length);
var tokens = query.toLowerCase().split('/');
var keyword = tokens.join(" ");
var bodyContent = "Looks like you came from an old bookmark, or just looking for a page that doesn't exist. Were you looking for <span class='tg'><a href='/search/"+ escape(keyword) +"'>"+keyword+"</a></span>";
bodyNode.previousSibling.innerHTML = bodyContent;
}
}
</script>
I was research this problem too, and I found a answer.
If you gotta to 404 Error page, that post is no have any PostID,
so you can just check {PostID} is null or not to check it is 404 page.

chrome extension which will read text inside the particular TAG?

I am trying to create chrome extension which will read text inside the particular TAG from the Webpage ...
but not able to read value
I need to pick Text inside the tag definition excluding html tags..
here i want to read the value from the tag "definition"
output:is an overwhelming urge to have of something is often connected with money
suppose web page is like this
<div id="definition">
<div class="section blurb">
<p class="short"><i>Greed</i> is an overwhelming urge to have <i>more</i>
of something
<p class="long"><i>Greed</i> is often connected with money</p>
</div>
</div>
this is what i was trying
popup.html
<script>
var newwin = chrome.extension.getBackgroundPage();
newwin.get();
</script>
background.html
<Script>
function get()
{
var myDivObj = document.getElementById("definition");
if ( myDivObj ) {
alert (myDivObj.innerHTML);
}else{
alert ( "Alien Found" );
}
}
</Script>
I moved my script from the background page to content scrit and it worked like charm..
but was just wondering why dint work in background page..?

Make anchor links refer to the current page when using <base>

When I use the HTML <base> tag to define a base URL for all relative links on a page, anchor links also refer directly to the base URL. Is there a way to set the base URL that would still allow anchor links to refer to the currently open page?
For example, if I have a page at http://example.com/foo/:
Current behaviour:
<base href="http://example.com/" />
bar <!-- Links to "http://example.com/bar/" -->
baz <!-- Links to "http://example.com/#baz" -->
Desired behaviour:
<base href="http://example.com/" />
bar <!-- Links to "http://example.com/bar/" -->
baz <!-- Links to "http://example.com/foo/#baz" -->
I found a solution on this site: using-base-href-with-anchors that doesn't require jQuery, and here is a working snippet:
<base href="https://example.com/">
/test
Anchor
Or without inline JavaScript, something like this:
document.addEventListener('DOMContentLoaded', function(){
var es = document.getElementsByTagName('a')
for(var i=0; i<es.length; i++){
es[i].addEventListener('click', function(e) {
e.preventDefault()
document.location.hash = e.target.getAttribute('href')
})
}
})
Building upon James Tomasino's answer, this one is slightly more efficient, solves a bug with double hashes in the URL and a syntax error.
$(document).ready(function() {
var pathname = window.location.href.split('#')[0];
$('a[href^="#"]').each(function() {
var $this = $(this),
link = $this.attr('href');
$this.attr('href', pathname + link);
});
});
A little bit of jQuery could probably help you with that. Although base href is working as desired, if you want your links beginning with an anchor (#) to be totally relative, you could hijack all links, check the href property for those starting with #, and rebuild them using the current URL.
$(document).ready(function () {
var pathname = window.location.href;
$('a').each(function () {
var link = $(this).attr('href');
if (link.substr(0,1) == "#") {
$(this).attr('href', pathname + link);
}
});
}
Here's an even shorter, jQuery based version I use in a production environment, and it works well for me.
$().ready(function() {
$("a[href^='\#']").each(function() {
this.href = location.href.split("#")[0] + '#' + this.href.substr(this.href.indexOf('#')+1);
});
});
You could also provide an absolute URL:
<base href="https://example.com/">
test
Rather than this
test
I'm afraid there is no way to solve this without any server-side or browser-side script. You can try the following plain JavaScript (without jQuery) implementation:
document.addEventListener("click", function(event) {
var element = event.target;
if (element.tagName.toLowerCase() == "a" &&
element.getAttribute("href").indexOf("#") === 0) {
element.href = location.href + element.getAttribute("href");
}
});
<base href="https://example.com/">
/test
#test
It also works (unlike the other answers) for dynamically generated (i.e. created with JavaScript) a elements.
If you use PHP, you can use following function to generate anchor links:
function generateAnchorLink($anchor) {
$currentURL = "//{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$escaped = htmlspecialchars($currentURL, ENT_QUOTES, 'UTF-8');
return $escaped . '#' . $anchor;
}
Use it in the code like that:
baz
To prevent multiple #s in a URL:
document.addEventListener("click", function(event) {
var element = event.target;
if (element.tagName.toLowerCase() == "a" &&
element.getAttribute("href").indexOf("#") === 0) {
my_href = location.href + element.getAttribute("href");
my_href = my_href.replace(/#+/g, '#');
element.href = my_href;
}
});
My approach is to search for all links to an anchor, and prefix them with the document URL.
This only requires JavaScript on the initial page load and preserves browser features like opening links in a new tab. It also and doesn't depend on jQuery, etc.
document.addEventListener('DOMContentLoaded', function() {
// Get the current URL, removing any fragment
var documentUrl = document.location.href.replace(/#.*$/, '')
// Iterate through all links
var linkEls = document.getElementsByTagName('A')
for (var linkIndex = 0; linkIndex < linkEls.length; linkIndex++) {
var linkEl = linkEls[linkIndex]
// Ignore links that don't begin with #
if (!linkEl.getAttribute('href').match(/^#/)) {
continue;
}
// Convert to an absolute URL
linkEl.setAttribute('href', documentUrl + linkEl.getAttribute('href'))
}
})
You can use some JavaScript code inside the tag that links.
<span onclick="javascript:var mytarget=((document.location.href.indexOf('#')==-1)? document.location.href + '#destination_anchor' : document.location.href);document.location.href=mytarget;return false;" style="display:inline-block;border:1px solid;border-radius:0.3rem"
>Text of link</span>
How does it work when the user clicks?
First it checks if the anchor (#) is already present in the URL. The condition is tested before the "?" sign. This is to avoid the anchor being added twice in the URL if the user clicks again the same link, since the redirection then wouldn't work.
If there is sharp sign (#) in the existing URL, the anchor is appended to it and the result is saved in the mytarget variable. Else, keep the page URL unchanged.
Lastly, go to the (modified or unchanged) URL stored by the mytarget variable.
Instead of <span>, you can also use <div> or even <a> tags.
I would suggest avoiding <a> in order to avoid any unwanted redirection if JavaScript is disabled or not working, and emulate the look of your <a> tag with some CSS styling.
If, despite this, you want to use the <a> tag, don't forget adding return false; at the end of the JavaScript code and set the href attribute like this <a onclick="here the JavaScript code;return false;" href="javascript:return false;">...</a>.
From the example given in the question. To achieve the desired behavior, I do not see the need of using a "base" tag at all.
The page is at http://example.com/foo/
The below code will give the desired behaviour:
bar <!-- Links to "http://example.com/bar/" -->
baz <!-- Links to "http://example.com/foo/#baz" -->
The trick is to use "/" at the beginning of string href="/bar/".
If you're using Angular 2 or later (and just targeting the web), you can do this:
File component.ts
document = document; // Make document available in template
File component.html
<a [href]="document.location.pathname + '#' + anchorName">Click Here</a>

add dynamically data-role pages

I want add dynamically data-role pages in my phonegap application. I thought that I can do this with something like this but isn't working
jQuery(function()
{
var theList = jQuery('#results');
for(i=0; i<mytool_array.length; i++)
{
content = '<div data-role="page" id="page'+i+'"><div data-role="header" data-backbtn="false"></div><div data-role="content"><p>page=+'+i+'</p></div></div>';
theList.append(content);
}
})
Im my HTML:
<div id="results"></div>
As far as I can predict the problems are:
you shouldn't put pages in a div. they should be in body
your function starts at DOMready, so it is after (or partially during) jquery mobile makes its formatting
rethink your idea. putting basic html structure in body and filling them later should work better
Consider making it a list or a set of collapsibles instead of pages.
This said, your current code should look like this:
jQuery(function($)
{
var b = $('body');
for(i=0; i<mytool_array.length; i++)
{
$('<div data-role="page" id="page'+i+'"><div data-role="header" data-backbtn="false"></div><div data-role="content"><p>page=+'+i+'</p></div></div>') //newline added for readability. it shouldn't be here
.appendTo(b).page(); //newline added for readability
}
});