Unobtrusive Javascript for Links in New Windows

2010 January 15
by ericsal

As we all know, the “target” attribute is not valid in the XHTML Strict Doctype. That can be kind of a pain in the butt when you want to open a link in a new window.

If you’re using the Transitional Doctype you can do something like this:

<a href="http://www.wehaventthetime.com" target="_blank">WeHaventTheTime</a>

But for the Strict Doctype, that’s a big “no, no.” However, here’s a quick unobtrusive javascript solution for getting your links to open in a new window.

Now, with the code above, you just have to add the class “external-link” to any anchor tag in the HTML, and the JS will handle the rest.

<a href="http://www.wehaventthetime.com" class="external-link">WeHaventTheTime</a>

I guess I should probably take my own advice now, and apply the script to this blog… Do as I say, kids, not as I do.

Comments are closed.