I've created a website for a project I'm doing. In the content of the website there are some links for external web pages that can be visited. In the mean time when the user clicks on one of the links he'll be taken to the specified link and he will not be on the current page anymore. What I wanted to do is have the specified website in the link clicked appear in a new tab when the user clicks on the link. This way the user stays on the current page he's one and also can view the other page on the new tab.
I've looked on the internet and found this which seemed to be useful:
function externalLinks()
{
var anchors = document.getElementsByTagName("a");
for (var i=0; i<anchors.length; i++)
{
var anchor = anchors[i];
if(anchor.getAttribute("href"))
anchor.target = "_blank";
}
}
window.onload = externalLinks;
The problem I'm facing is that the navbar of my website contains anchor tags. So now if the user clicks on the links on the navbar it will open a new tab. I want this to happen ONLY if the user clicks on a link in the content of my website. So if the user clicks on a link in the navbar it shouldn't open a new tab and should just take him to the specified destination.
I've tried adding a class to all the links in the content and use getElementByClassName but it still didn't work
Anyone can help me with this
If you need to rely on JavaScript:
Basically you just need to change your
if
-condition (to check whether the anchor link points to an external location or not).So, instead of
if(anchor.getAttribute("href"))
, useif(anchor.getAttribute("href") && anchor.hostname!==location.hostname)
.With a bit of code clean up, your function should look as follows:
You can just use HTML:
Another Example:
This takes advantage of the target attribute.
More information on the target attribute: http://www.w3schools.com/tags/att_a_target.asp Also: http://www.w3schools.com/html/html_links.asp
EDIT:
For XHTML, just do this:
Or, again:
you want to use
document.getElementById("theidgoeshere");
To do this, set the id attribute in your link like so:
Then in your javascript
Also note you might want to do without the javascript. Just put
target="_blank"
in your anchor tag.Are you required to use javascript for this?
If not you could just add the attribute directly to the a tag in the HTML.
For example:
<a href="http://www.google.co.uk" target="_blank">Google</a>
That would probably be an easier way for you to do it if javascript is not required.