Wednesday, February 10, 2010

Strict XHTML deprecates "target" attribute

The target attribute of the <a> tag is deprecated in HTML 4.0 Strict and XHTML 1.0 Strict: New-Window Links in a Standards-Compliant World

(Updated 2/12/2010 and 2/24/2010:)
I like the jQuery solution in Justin Scheetz's comment on this article in badlyDrawnToy:

$(function() {
  $("a[href*='http://']:not([href*='"+location.hostname+"'])").click( 

    function() {
      window.open(this.href);
      return false;
  });
});


(Updated again 2/24/2010:)
Here's the jQuery for just setting the target attribute (with a little help from NerdyDork):

$(function() {
$("a[href*='http://']:not([href*='"+location.hostname+"'])").attr("target", "_blank");
});


(Updated again 10/06/2011:)
Found earlier that the above solution failed for https, so I had to add another line for that.  And then found that the comparison for .hostname needs to be case-insensitive.  So my latest solution is the following, using some tips from the electric toolbox (which also mentions that, with HTML5, "the W3C has un-deprecated the target attribute"):

$(function() { 
  $("a").filter(function() { 
    // find all links that have a hostname 
    // that doesn't match the current location
    return this.hostname && 
      this.hostname.toLowerCase() !== location.hostname.toLowerCase();
  }).click(function() { 
    // open those external links on another window 
    window.open(this.href); 
    return false
  }); 
})



5 comments:

  1. So the new way is to flag the relevant tags and then use JavaScript to iterate through all the tags on a page to see if any of them have the tag? Good grief, whose decision was it to make the code more verbose and add a bunch of unnecessary cycles by checking all the tags? :|

    ReplyDelete
  2. No kidding. And did you see the date on that article? 2003! Maybe there's a better way to do it now. I'll need to check.

    ReplyDelete
  3. Haha, I'm so 2003. Yeah I think I'd prefer to just slap a function on individual links that would call window.open.

    ReplyDelete
  4. Updated the post with a jQuery solution from http://www.badlydrawntoy.com/2009/03/03/replacing-target_blank-for-strict-xhtml-using-jquery-redux/.

    ReplyDelete
  5. Fixed the outer double-quotes in the jQuery code. It works great.

    ReplyDelete