Saturday, June 28, 2008

How to target="_blank" a link while keeping it XHTML compliant with jQuery

I had to make a bunch of links for a site I am working on for a client at work open in a new window.  It's not ideal but it was what was requested.

So I set up my links like such:

<a href="http://damnralph.com" target="_blank">http://damnralph.com</a>

I run my page though a HTML validator and am quickly reminded that the target attibute is not allowed in the XHTML 1.0 Strict standard.  I do a quick Google Search and the first couple of results bring back the following function to make it compliant:

function externalLinks() {
 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") &&
       anchor.getAttribute("rel") == "external")
     anchor.target = "_blank";
 }
}
window.onload = externalLinks;

This function expects there to be a rel="external" attribute inside the links you want to open in a new window.

That function to me looks scary and ugly.  jQuery to the rescue.

$(document).ready(function(){
    $("a[rel='external']").attr("target","_blank");
});

I was able to shrink all that down to one line of jQuery.  And it's a lot easier to read and more importantly it now makes the document XHTML compliant.

Note: I did notice a huge argument/discussion on if this is really truely standards compliant.  As when you take the generated html code and run that through the validator you still get the same compliance error.  While others say that you are separating the action from the presentation and that satisfies the standard.  Thirdly others say that target was depricated and as such we should never use it because the standards people think we shouldn't open new windows on people.   I don't know whose right or whose wrong but I did find the discussion interesting.  Thoughts?

Monday, June 30, 2008 2:11:24 PM (Eastern Daylight Time, UTC-04:00)
I used to use class="new" but I like rel="external" much better. I'm of the standards camp that likes to keep even the generated code valid, so:

$(document).ready(function(){
$("a[rel='external']").onclick(function () {
window.open(this.href);
return false;
});
});

The main reason for me is because browsers can ignore the "target" attribute at any time and I don't want to go back and change all my code.
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, b, blockquote@cite, em, i, strike, strong, sub, super, u)  

Enter the code shown (prevents robots):

Blog Posts by:

Currently Viewable:

My Twitter Updates

View Twitter Page