External Linking with XHTML and jQuery

| | 1 Comment

Many of you may be familiar with the behavior on this blog and the Panda’s Thumb that links to external websites open a new window or tab. In old fashioned html, this would be accomplished by adding a “target” attribute to your link:

<a href="http://scit.us/" target="_blank">Scitus</a>

However, with the advent of XHTML, content was separated from style and behavior, and the target attribute was officially retired; although, it is still recognized by standard browsers. Instead with XHTML, the proper solution is to use the “rel” tag to show how the linked page is connected to the current page:

<a href="http://scit.us/" rel="external">Scitus</a>

Perhaps you are using a browser that understands this but are probably not; therefore, we use a line of javascript to tell the browser what to do with those links:

$(function(){$('a[href][rel*=external]').each(function(i){this.target = "_blank";});});

The above code is very cryptic because it relies on shortcuts provided by the jQuery library. With prototype you can do use something equally cryptic like this:

function externalLinks() {
	$$('a[href][rel~=external]').each( function(value, index) {value.target = "_blank";});
}
Event.observe(window, 'load', externalLinks, false);

Sure, it’s more complicated than the original, but it wouldn’t be progress if unless they made things harder to do.

1 Comment

Thanks for the tip, working great on my site.

About this Entry

This page contains a single entry by Reed A. Cartwright published on February 23, 2008 11:55 AM.

WΔZ: Evolutionary Equations on the Big Screen was the previous entry in this blog.

Green Openlab is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Archives

Powered by Movable Type 4.37