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
<a target="_blank" href="YourAmazingURL">Click here for Amazing URL</a>
Another Example:
<a target="_blank" href="http://www.google.com/">Google</a>
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:
<a href="YourAmazingURL" onclick="window.open(this.href,'_blank');return false;">Click here for Amazing URL</a>
Or, again:
<a href="http://www.google.com/" onclick="window.open(this.href,'_blank');return false;">Google</a>
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.
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"))
, use if(anchor.getAttribute("href") && anchor.hostname!==location.hostname)
.
With a bit of code clean up, your function should look as follows:
function externalLinks() {
for(var c = document.getElementsByTagName("a"), a = 0;a < c.length;a++) {
var b = c[a];
b.getAttribute("href") && b.hostname !== location.hostname && (b.target = "_blank")
}
}
;
externalLinks();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With