Target _blank is out the window

Posted by on Aug 15, 2012 in Code Chat, JavaScript | No Comments

Clients will often ask me to target external site links to open in a new window. Of course the correct answer is

“No, it’s not up to a site to determine how a link should work, the user can decide that when browsing.”

Not only is it bad practice but the target=”_blank” tag has been depreciated now and will cause a page to fail strict validation.

The truth is though that it is important to avoid taking traffic away from your site and whenever I have launched my own sites I find myself trying to achieve the same thing.

So here’s my solution

Use JavaScript to look through all links, determine whether they link to another domain and add the target after the page loads. This way the page will still validate, the code will be tidier and you won’t have to remember to manually change the link target every time one is added.


$("a[href^=http]").each(
function(){
nonwww = location.hostname.replace("www.", "");
if(this.href.indexOf('http://'+location.hostname) == -1 && this.href.indexOf('http://'+nonwww) == -1) {
$(this).attr('target', '_blank');
}
}
)

 

Leave a Reply