External links in new windows without using 'target'

The default Drupal 5.0 theme (and previous default Drupal themes) uses XHTML Strict. There are reasons this is probably a bad idea but, in the spirit of eating my own dogfood, I'm going with it for now.

One gotcha I discovered right away is that the <a> tag does not allow the "target" attribute in XHTML Strict (nor does it in HTML Strict). However, the behavior of <a target="_blank"'> can be replicated in XHTML Strict with semantic markup and scripting.

Start by replacing the "target" attribute with the "rel" attribute:

<a href="url" rel="external">

Next, add a little bit of jQuery:

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

This finds all anchor tags with rel="external" and causes them to open a new window when clicked. The "return false;" prevents the current page from switching to the URL as well. As an added benefit, these links get the CSS class "external" so they can be styled, perhaps with something like:

A.external {
  padding-left: 15px;
  background: url(external-link.png) top left no-repeat;
}

If JavaScript is not enabled, the link will behave as normal.

Comments

Ever thought of letting the

Ever thought of letting the visitor decide whether s/he wants to open the link in a new window or not? That's basically the whole idea behind getting rid of target in the strict versions.

I understand, that in some situations you may want to have it opened in a new window, but most of the time it's an annoyance to many users.

Please don't open links in

Please don't open links in new windows.

Ever.

Please?

sometimes it is really

sometimes it is really useful...

I was quite surprised by the

I was quite surprised by the negative responses to this article. I created a poll so I could get a (slightly) more accurate idea of how people feel about opening new windows for external sites. Please cast your vote!

I prefer to let the user

I prefer to let the user decide but the external-link icon is a nice visual clue. So this code is very useful.

why? ? ? I might want to

why? ? ? I might want to keep my site active while giving the user an informative link!

It all depends on context.

It all depends on context. Letting the user decide is most friendly. If I right-click on a link (Mac equivalent = CTRL-click?) I can open the link in a new window or not. Foreshadowing, as you do with the icon, is okay, except that nobody except for experienced Barry Jaspan website visitors knows what it means.

The comments on this article

The comments on this article have been pretty strongly against opening external links in new windows. In the poll results, however, 71% of respondents favor it (some only with a visual/semantic indicator).

What's up with that?

Hi, thanks for this

Hi,

thanks for this technique, it's a very neat way of doing it. A client (and friend) whose site I developed and maintain has asked me to make external links open in new windows. I initially persuaded him this was a bad idea and explained that users should be given the choice how they want to browse, since it is easy enough for them to open links in a new window if they wish to do so. However he has insisted, largely because he is paranoid that when people follow links to external sites they will forget about his site, and ultimately spend less time on it clicking his ad links!

It's all very well insisting on best practise and respect for our freedoms as users, but sometimes our paymasters force our hand, and in those situations techniques like this are much needed to give us a way of implementing these necessary evils as elegantly as possible.

cheers,
Ben

I find when I am reading

I find when I am reading blogs or news sites I would much rather links I clicked opened in a new window (or tab since I am using Firefox) than taking me away from the article I am reading. I'm in the habit of holding down CTRL while I click anything so most things are forced into a new tab anyway. I am making up a site for my friend to show off his art and had trouble with the site not validating because I had used the target attribute (using XHTML Strict doctype). Thanks for the solution.

Novice users need protection

Novice users need protection from themselves. Some users do not know how to force a link to open in a new window (my dad for example).

I wanted to put the W3C Valid Icon on my page. But face it, most people have never heard of the W3C or XHTML and they don't care. If they clicked the Validator Icon out of curiosity and consequently get redirected away from the site they were browsing, I think some would be confused and/or agitated.

I will concede though, if they make it far enough through the page to click an icon at the foot of the document, one could argue the person had completed browsing the page.

I always, always open links

I always, always open links in a new window/tab when browsing. I would love to make the links I create on my website, Any Given Tuesday, open in a new page, but it seems like everyone is opposed to doing that! I think my fear, that visitors will click on a band's name or an album title and disappear never to return, is quite valid. But netiquette controls, apparently.

Yup, it annoys visitors.

Yup, it annoys visitors.

Good discussion. I'm

Good discussion. I'm guessing the only people irritated by forced "new window" links are the people that no how to make a normal link open in a new window, and I agree that the user should have the control. Fact is, most of the web viewing community does not know how to do this, or does not do it regularly. The solution is not on the web designing communitie's shoulders—I intend to maintain the status quo (internal links in the same window & external links in a new window—all while practicing standards compliance of course). This improvement to the online UX should be built into browsers: any link that has a default behaviour, such as (not) opening in a new browser window, should be completely overridable. I don't know about any other browsers, but Safari, pretty much does this by holding the command key (all links, regardless of their default behaviour, open in a new tab instead).

I'm amused that the

I'm amused that the discussion has centered on the lawfulness of opening links in new windows, but no one has commented on the code itself -- that JQuery snippet fails because there are 2 periods between the "external" class (at the end of the line) and the onclick (at the beginning).

Also, recent versions of jQuery make you type .attr('href') instead of .href

That said, thanks -- I was glad to quickly find window.open() (for use with jQuery) without having to wade through 15 lines of DOM traversal code.

Instead of giving a class to

Instead of giving a class to all external links, JQuery can help us to find external links.

$('a[@href^="http://"]').addClass('external').attr('target', '_blank');

Add a class of "external" to all external links (those beginning with http://), then add target="_blank" for good measure (taken from http://simonwillison.net/2007/Aug/15/jquery/).

Happy programming...

Thanks for your comment. I

Thanks for your comment. I see two problems with your suggestion, though:

  1. Not all links that start with http:// are external. Especially on a site with user-contributed content, links to the local site might start with http://. Also, there can be external links that start with https:// or other protocols.

  2. Adding target=”_blank” is exactly what we are trying to avoid as it is not valid HTML Strict or XHTML Strict.

I think the developer should

I think the developer should be free to open links in new windows. The browser problem then is not about allowing users to open links in new windows if they want, but allowing users to force all links to open in the same window if they want ... which I don't understand why a user would want to do. Do browsers do that? Would it make sense for them to do that?

It doesn't work with

It doesn't work with Internet Explorer, but it works with Firefox and Opera. So, when does Internet Explorer ever do anything right? Many people do not even know how to enable JavaScripts on IE, and it seems IE does not pay attention to all JavaScripts anyway. Between W3C not allowing the target="_blank" attribute and browsers not automatically opening new windows in new tabs with this code, something tells me that doing all this handiwork will soon have to be resolved in a more conventional way.

Web developers shouldn't have to do a lot of tinkering with their code or even resort to scripts for a simple task like opening a new window. Let Bill Gates contend with it, I say. In the meantime, I guess I will just have to rely on visitors not using IE. I won't use the target="_blank" code while it still opens an entirely new instance of IE. I hate that, and I am sure other people do too. It is better to just rely on the visitor being able to find his way back if he is inclined. The code that I used to do the same thing came from another JavaScript author off another site. It does the same thing. It is as follows:

function external() {
if (document.getElementsByTagName) {
  var i, a;
  a = document.getElementsByTagName('a');
  for (i in a) {
   if (a[i].getAttribute('href') &&
       a[i].getAttribute('rel') == 'external') a[i].target = '_blank';
  }
}
}
window.onload = external;

You have to put the code into an external style sheet in order for your page to validate on W3.Org. Then you can create a link using the rel="external" code.

You can change the Web! Join W3C today!

Check out this bit of news

Check out this bit of news from W3C. It is about how hyperlinks might be handled in CSS3! It is simply exciting stuff!
Click here to go to the article on W3.Org.

Developers shouldn't have to

Developers shouldn't have to do a lot of tinkering with their code or even resort to scripts for a simple task like opening a new window. Let Bill Gates contend with it, I say. In the meantime, I guess I will just have to rely on visitors not using IE.

What are the browsers that

What are the browsers that support rel="external" attribute? I've used it a few times in my blogs, but I don't see how it works. It's totaly ignored by IE and FF. Didn't try with other browsers. I suppose it will eventually be a trigger for opening a new window for a given link. But not now.

Let the readers decide?

Let the readers decide? Well... I agree, let them decide if they want to open the pages in the same window too, then. Regardless of your default option they can do whatever they want. I supply those links as an "additional" resource and it has nothing to do with my content being insufficient. I don't want my readers to go somewhere in the mids of reading something and gets lost in those new pages. If they want to however, they can either close my tab/window. Choice is theirs.

I always used "rel" attrebute

I always used "rel" attrebute and never new that "target" can cause trouble :)

Anyone who is annoyed by

Anyone who is annoyed by links being opened in new windows is receiving that annoyance as karma for not having enough sense to A. use Firefox, and B. utilize the "Tab Mix Plus" add-on, which gives the option to set a default action where all new window links are forced into a new tab instead.

The correct code is

The correct code is :

$(document).ready( function() {
    $('A[rel="external"]').addClass("external").click( function() {
        window.open( $(this).attr('href') );
        return false;
    });
});

As seen on http://abeautifulsite.net/notebook/47

I think new windows are great

I think new windows are great for certain audiences, I'm designing a site for a coaching holiday firm, whose customers are mostly over 60, with external link to hotel websites.
I'm
* pretty sure they wont know how to open a link in a new window for themselves.
* doubt they are using Firefox.
* think they are more likely to go back to the original site if they can see it open in another window on there task bar etc, rather than having to click Back several times (after they have checked if the hotel has tea/coffee making facilities).

Personally I prefer new windows opening to external sites, I have enough things to worry about and remember without needing to know which page I was browsing when I went off on a tangent, this new rule is too complicated for the average user.

greet post I speeck on my

greet post I speeck on my blog

http://www.telavenir.com

Anyone who is not happy by

Anyone who is not happy by this links being opened in new windows is receiving that annoyance as karma for not having enough sense to A. use Firefox, and B. utilize the "Tab Mix Plus" add-on, which gives the option to set a default action where all new window links are forced into a new tab instead.

I use a desktop to do

I use a desktop to do research and get news. Most people don't research, or read news for that matter. So I'm different. I don't want to spend time getting daily info, so I coded a page for my desktop. If the links do not open in new tabs, the operation is open page, click link, read, go back (maybe several times), click link, etc., and that's hoping the browser can negotiate through the history (which often fails because of 'marketing!' Closing tabs is a matter of clicking the close button. Way simpler and faster. My original page stays in place in the first slot. Have it your way. Of course with mobile devices, the issue presents a whole different face, so the W3 may be right.

I think it's ridiculous

I think it's ridiculous people are complaining about links opening in another window. It's annoying to me when I click on a link I know should lead offsite, but it does NOT open in a new window (well new tab technically) and I have to go back to the page I was looking at. Who in the world does NOT have a browser with tabs (and if you don't then that's pretty sad-- Opera and FireFox are both great and free), AND you can set new tabs to open in the background, so it isn't even an issue. duh. we are talking about new windows not popup ads or something annoying.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <i> <h1> <h2> <h3> <blockquote>
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options