December 20, 2011

Simple Workaround for Strict HTML Validation of _blank Target

There are times when it's legitimate to automatically open up a link in a new tab or window of the user's web browser.  Setting the link's "target" attribute to "_blank" used to be the correct way to realize this behavior.

<a href="http://www.snapbackup.org/" target="_blank">backup</a>
Obsolete Usage

Partly because the target expresses behavior instead of content, the "target" attribute has been depreciated and does not pass validation for strict HTML or HTML5.  There's a cheap and dirty JavaScript trick that achieves the desired behavior and still validates.

<a href="http://www.snapbackup.org/" onclick="this.target='_blank';">backup</a>
Compact (and valid HTML) Workaround

Example link with "_blank" target:
This workaround does pollute the semantics of the HTML with behavior instructions, but it's compact, easy to understand, and validates.

For sites with jQuery, you can keep the HTML cleaner by using the "rel" attribute to designate external links and then adding targets with a jQuery selector.

1 comments:

Julian H said...

Don't do this. While you may fool your validator by doing this, you're not creating valid HTML. A more sophisticated validator would check the runtime attributes on your link or simply validate the Javascript.

You can use a class name or rel attribute that gets post-processed by javascript (either jQuery or otherwise) to change the click behavior to open a new window.

Better yet, you can decide that you don't actually care about passing the test for validity. While using a validator as a tool is an extremely good habit and can help save you a lot of time, the results of the validator should not be taken as gospel. They should simply be taken into consideration. Code quality is far more important than code validity.