Target to a page inside an iframe - html

I will try to explain again:
I have 3 images in my index.html that when clicked i'd like to point respectively to ourmission.html, ourvalues.html and ourvision.html.
But this 3 pages are inside an iframe located in the page ourcompany.html as you can see below:
<aside class="sidebar">
<h4>Our Company</h4>
<ul class="nav nav-list primary pull-bottom">
<li>Contact Us</li>
<li>Our Mission</li>
<li>Our Values</li>
<li>Our Vision</li>
</ul>
</aside>
<iframe src="contactus.html" frameborder='0' name="conteudo" width="700" height="700">
</iframe>
How do i to point them directly, so the page ourcompany.html will load with the specific iframe opened.

This might be a possible solution for you, if I have understood you correctly.
I am assuming you dont have a server set up with the website.
In your index.html, your image links need to be modified to this:
<img src="" />
<img src="" />
<img src="" />
Notice the ?link=someValue after the ourcompany.html link. This is a GET request but you will use it to pass data between pages.
Now in your ourcompany.html page you need to get the value you sent after the ?link=. So you need to add some Javascript. This is the function you need to add to ourcompany.html:
function getValue()
{
// First, we load the URL into a variable
var url = window.location.href;
// Next, split the url by the ?
var qparts = url.split("?");
// Check that there is a querystring, return "" if not
if (qparts.length == 0)
{
return "";
}
// Then find the querystring, everything after the ?
var query = qparts[1];
// Initialize the value with "" as default
var value = "";
var parts = query.split("=");
// Load value into variable
value = parts[1];
// Convert escape code
value = unescape(value);
// Return the value
return value;
}
Now you can change the iframe src attribute accordingly like this:
var link = getValue();
if (link.length){//check if you got a value
document.getElementByName('conteudo').src = link + ".html";//set the src
}

I got the solution adding the following code to the page where the iframe is located:
<script>
window.onload = function loadIframe(){
if (location.search.length > 0){
url = unescape(location.search.substring(1))
window.frames["iframe-name"].location=url
}
}
</script>
and using the href as:
<a href="iframe-page.html?specific-iframe.html">
Thanks a lot for everyone that tried to help me.

Related

Attempting to remove anchor tags from the URL

Situation: I want to remove the anchor tags ( #tag ) from the end of the URL
What I have tried: I have been following "https://www.finsweet.com/hacks/15/" and "https://stackoverflow.com/questions/34175285/removing-anchor-tags-from-url". Its not working out very well though.
Code:
My snippet from the top nav bar
<ul class="nav">
<li class="scroll-to-section">
Home
</li>
</ul>
My use of Id
<div class="main-banner header-text" id="top">
Maybe the way i approached the edits to the navigation bar is wrong.. but im not sure what i need to to do to achieve the goal. Or how I used the classes and IDs is possibly incorrect?
--- Edit 1 ---
this is the snipper of the script im attempting to use to remove the anchor tag from the URL bar of a brower.
$("#js-anchor").click(function (evt) {
evt.preventDefault();
var anchor = $(this).text();
$("html, body").animate(
{
scrollTop: $("#" + anchor).offset().top,
},
1500
);
});
And the html im looking at
<li class="scroll-to-section">
<a id="js-anchor" href="#testimonials" class="active"
>staff</a>
</li>
The experment on it is here:
https://the-md.studio/indexhash.html
EDIT2
My new attempt
<li class="scroll-to-section">
Home
</li>
JS
$(document).ready(function () {
// get the anchor link buttons
const menuBtn = $(".scroll-to");
// when each button is clicked
menuBtn.click(() => {
// set a short timeout before taking action
// so as to allow hash to be set
setTimeout(() => {
// call removeHash function after set timeout
removeHash();
}, 5); // 5 millisecond timeout in this case
});
// removeHash function
// uses HTML5 history API to manipulate the location bar
function removeHash() {
history.replaceState(
"",
document.title,
window.location.origin + window.location.pathname + window.location.search
);
}
});
Just saw this Q. I guess this is what you tried to ask:
// first: get the full url
var hash_url = window.location.href;
// second: simply do a split
// can't go wrong here, because url's that show content are always in correct format
hash_url = hash_url.split('#'); var clean_url = hash_url[0];
alert(clean_url);
There's your clean url!

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

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");.

why document.getElementsByName().length always return 0?

I'm new to JavaScript. In the following code getElementsByName("li").length always returns 0 although there are many <li>-tags in my HTML, why?
document.addEventListener('DOMContentLoaded', function() {
var len = document.getElementsByName('li').length;
alert(len);
})
art of my HTML:
<body>
<ul>
<li>aaaaaa</li>
<li>bbbbbb</li>
<li>cccccc</li>
</ul>
</body>
Replace
document.getElementsByName('li')
with
document.getElementsByTagName('li')
This is happening cause you are selecting by tag name and not by name ! You are using wrong function!
The method you are attempting to use is trying to find a specific element by its name.
None of your list items have a name, to do this you should update your code so that your items have names.
document.addEventListener('DOMContentLoaded', function() {
var len = document.getElementsByName('list_item_1').length;
alert(len);
})
<li name="list_item1">aaaaaa</li>
You can do something like this because getElementsByTagName() returns NodeList so you can iterate over it like an array or get the length.
document.addEventListener('DOMContentLoaded', function() {
var listElements = document.getElementById('list').getElementsByTagName("li");
alert(listElements.length);
})
<body>
<ul id="list">
<li >aaaaaa</li>
<li>bbbbbb</li>
<li>cccccc</li>
</ul>
</body>
getElementsByName() although also returns NodeList but it returns list of all same name elements in the whole document so to make this work you need to give same name to all list items.
document.addEventListener('DOMContentLoaded', function() {
var len = document.getElementsByName('name').length;
alert(len);
});
<body>
<ul>
<li name="name">aaaaaa</li>
<li name="name">bbbbbb</li>
<li name="name">cccccc</li>
</ul>
</body>

Changed "name" attribute to "id" but images don't show

Error: The name attribute on the img element is obsolete. Use the id attribute instead.
<img src name="slide" width="1714" height="500" alt="slideshow" />
Above you can see I have this error that's asking me to change the 'name' to 'id', however when I try this it end's up making my images not appear. So essentially the 'id' doesn't work but the 'name' does. Any ideas?
https://gyazo.com/ff5c6b39d5a1b649027d2fca57a1ffa1
As you can see in the first image the code is working when it is
<img src name=""/>
<script>
var i = 0; // Start Point
var images = []; // Images Array
var time = 3000; // Time Between Switch`
// Image List
// This holds an array of all my images
images[0] = "images/img_house.png";
images[1] = "images/img_staff.jpg";
images[2] = "images/img_desk.jpg";
images[3] = "images/img_coinstack.jpg";
// Change Image
function changeImg() {
document.slide.src = images[i];
// Check If Index Is Under Max
if (i < images.length - 1) {
// Add 1 to Index
i++;
} else {
// Reset Back To O
i = 0;
}
// Run function every x seconds
setTimeout("changeImg()", time);
}
// Run function when page loads
window.onload = changeImg;
</script>
<section>
<img src name="slide" width="1714" height="500" alt="slideshow" />
</section>`
Below I have changed the code to <img src id=""/> and it no longer works, it shows the alt text.
https://gyazo.com/634a5fa6db7e1acf22a55815f19d6da2
In your function you insert it using the name attribute "slide". But an id is not a name and must be fetched from the document. So
document.getElementById("slide").src = images[i];
Also, the <img> tag does not use or need a closing slash.

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>