views:

2452

answers:

11

I know that most links should be left up to the end-user to decide how to open, but we can't deny that there are times you almost 'have to' force into a new window (for example to maintain data in a form on the current page).

What I'd like to know is what the consensus is on the 'best' way to open a link in a new browser window.

I know that <a href="url" target="_blank"> is out. I also know that <a href="#" onclick="window.open(url);"> isn't ideal for a variety of reasons. I've also tried to completely replace anchors with something like <span onclick="window.open(url);"> and then style the SPAN to look like a link.

One solution I'm leaning towards is <a href="url" rel="external"> and using JavaScript to set all targets to '_blank' on those anchors marked 'external'.

Are there any other ideas? What's better? I'm looking for the most XHTML-compliant and easiest way to do this.

UPDATE: I say target="_blank" is a no no, because I've read in several places that the target attribute is going to be phased out of XHTML.

+7  A: 

Why is target="_blank" a bad idea?

It's supposed to do exactly what you want.

edit: (see comments) point taken, but I do think that using javascript to do such a task can lead to having some people quite upset (those who middle click to open on a new window by habit, and those who use a NoScript extension)

Luk
It will cause the XHTML validator to show an error, because it has been removed from the standard. Personally, I think that was a bad move. Now people come up with sh*t like "<span onclick>" just to get around it and still be "valid".
Tomalak
In XHTML 1.0 Strict and XHTML >1.1 "target" is not allowed attribute of "a" tag.
Damir Zekić
It think the problem is with Tabbed browsers. It is not clear whether this means open a new browser, open a new tab or open a sub window of the existing browser.
Martin Brown
Yes, standards... so this is totally not the answer. And I'm shocked there are so many people who upvoted this.
Kon
But I don't want it to be clear whether to open in a new tab or a new window. I want that to be up to the user.
Mark Baker
Yay, standards. Dosn't work well, but look, it's compliant.
Tomalak
Show me a browser that follows the standards :D
Gene
@fallen888 it depends on which standard you want to implement. I use XHTML 1.0 Transitional. FWIW, it is in HTML 5.0 and it does reappear, as far as I can tell, in XHTML 2.0.
tvanfosson
@Gene, Does that mean a developer shouldn't follow standards?
Kon
@Gene Safari (since long time manages to complete ACID 3 with 100%), Opera (development version does 100% on ACID 3), Firefox 3.1 is very close... And while 100% result on ACID 3 does not imply perfect support, it is far fetched to say that those browsers are not standards-compliant
Damir Zekić
@Mark: it is up to the user already. I can middle click for a new tab, or open a new window from the context menu. There's no way for you to differentiate between the two.
Adam Lassek
wow I learned something today oO
Luk
I've never cared and I don't see myself caring about standards anytime soon because of crap like this. Oh no, we've decided target is no good, so change everything! Well, my target attributes are staying put, and that's that.
Paolo Bergantino
@Paolo, no one said to change everything. But moving forward, I think it's a good idea to stay compliant.
Kon
+2  A: 

Perhaps I'm misunderstanding something but why don't you want to use target="_blank"? That's the way I would do it. If you're looking for the most compatible, then any sort of JavaScript would be out as you can't be sure that the client has JS enabled.

BoboTheCodeMonkey
You're right about the JS being enabled being a requirement. I think though that rel=external is an unobtrusive solution, because it's XHTML-compliant and forces an open in a different window only if JS is enabled.
Kon
For my in house IT application, certain form pages need to be created as new tabs. In Firefox they kept overwriting each other because I gave them a name, but this _blank page name allowed me to create more than one as needed all in their own tabs. So thanks for the tip.
Tony Peterson
A: 
<a href="http://www.google.com" onclick="window.open(this.href); return false">

This will still open the link (albeit in the same window) if the user has JS disabled. Otherwise it works exactly like target=blank, and it's easy to use as you just have to append the onclick function (perhaps by using JQuery) to all normal tags.

Mark S. Rasmussen
But surely you wouldn't want to put such an onclick handler on every link on your site that requires it be opened in a new window/tab.
Kon
Why not, while arguably too verbose it is certainly acceptable and in the spirit of the spec.
Evan Carroll
A: 

I say target="_blank" is a no no, because I've read in several places that the target attribute is going to be phased out of XHTML.

Kon
You've missed the point. target=_blank was removed not because method was wrong, but because goal was wrong. By trying to reach the same goal using other method you're still doing wrong thing against intent of the standard. Don't open new windows. If you want to open them anyway, use target=_blank.
porneL
The goal was to removing the scripting element from the markup of data, not to make the effect impossible. XHTML1.1 is proudly parse-able and enhanced with Javascript and its `window.open`.
Evan Carroll
+21  A: 

I am using the last method you proposed. I add rel="external" or something similar and then use jQuery to iterate through all links and assign them a click handler:

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

I find this the best method because:

  • it is very clear semantically: you have a link to an external resource
  • it is standards-compliant
  • it degrades gracefully (you have a very simple link with regular href attribute)
  • it still allows user to middle-click the link and open it in new tab if they wish
Damir Zekić
Yes, this seems to be my most recently favorite approach. Just wondering if anyone came up with any other slick way.
Kon
Having to jump through these hoops is probably why the target attribute reappears in XHTML 2.0.
tvanfosson
@tvanfosson a small correction: it reappears in XHTML5, not XHTML 2.0. XHTML5 is XML serialization of HTML5, while XHTML 2.0 is improvement on XHTML 1.1. Anyhow, rel="external" improves semantic, while target="_blank" is a behaviour directive (which should be left to JS)
Damir Zekić
Agreed with porneL, but the basic idea is good - use of rel=external.
Kon
Here is a great blog post covering this that uses the same method -- it might have been influenced by this. http://www.badlydrawntoy.com/2009/03/03/replacing-target_blank-for-strict-xhtml-using-jquery-redux/
Evan Carroll
You could easily convert that to a [`.live()`](http://api.jquery.com/live) event to catch events on `<a rel="external">` tags that are added after the page loads as well.
gnarf
Just a side note use rel*=external instead. Note the asterisk. If you have rel="external nofollow" it won't trigger without the asterisk. The asterisk is a search modfier, that says CONTAINS external.
Phliplip
@Philiplip good point, I've updated the code
Damir Zekić
A: 

If you use any flavor of strict doctype or the coming real xhtml-flavors, target isn't allowed ...

Using transitional, whatever being HTML4.01 or XHTML1, you can use Damirs solution, though it fails to implement the windowName-property which is necessary in window.open():

In plain html:

<a href="..." target="_blank" onclick="window.open(this.href, 'newWin'); return false;">link</a>

If however you use one of the strict doctypes your only way of opening links would be to use this solution without the target-attribute ...

-- by the way, the number of non-js-browsers is often miscalculated, looking up the counters numbers refer very different numbers, and I'm wondering how many of those non-js-browsers is crawlers and the like !-)

roenving
I deactivate js on "some" websites ;)
Luk
using name for window in window.open is *very* annoying - it will unexpectedly replace content of another window (it's problematic when same name is used for more than one link on the page)
porneL
But it is mandatory, so illegal code will be the result if you miss it ...
roenving
-- amd most browsers accept '_blank' as window-name to open a new browser-window (not all !-)
roenving
I haven't seen browser that doesn't accept _blank for window name. If you want to support such browser, you could use random name.
porneL
A: 

If I'm on a form page and clicking on a moreinfo.html link (for example) causes me to lose data unless I open it in a new tab/window, just tell me.

You can trick me in to opening a new tab/window with window.open() or target="_blank", but I might have targets and pop-ups disabled. If JS, targets and pop-ups are required for you to trick me into opening a new window/tab, tell me before I get started on the form.

Or, make links to another page a form request, so that when the visitor submits, the current form data is saved so they can continue from last time, if possible.

Shadow2531
It's not always under developer's control how the page should behave. I can't simply introduce 'helper' messages/comments on a large pharmaceutical firm's website.
Kon
True. FWIW, I see lots of sites that just use a javascript URI in the href to open a new window. Then, when JS is off, the link just doesn't work. Of course, target="_blank" will work just as good and will work with JS off. It may not validate, but it'll work, which is more important.
Shadow2531
A: 
<a href="http://some.website.com/" onclick="return !window.open( this.href );">link text</a>

Details are described in my answer to another question.

Fczbkk
+6  A: 

Please, don't force opening a link in a new window.

Reasons against it:

  • It infringes the rule of the least astonishment.
  • The back-button don't work and the user not possibly knows why.
  • What happen in tabbed browsers? New tab or new window? And whichever happens, is it what you wants, if you mix tabs and windows?

The reason I always hear in favor of opening a new window is that the user will not leave the site. But be sure, I will never come back to a site that annoys me. And if the site takes away control from me, that is a big annoyance.

A way may be, that you give two links, one is normal, the other opens it in a new window. Add the second with a little symbol after the normal link. This way users of your site stay in control of which link they want to click on.

Mnementh
A: 

Here is a plugin I wrote for jQuery

 (function($){  
  $.fn.newWindow = function(options) {       
    var defaults = {
     titleText: 'Link opens in a new window'  
    };

    var options = $.extend(defaults, options);

     return this.each(function() {  
       var obj = $(this);

       if (options.titleText) {        
        if (obj.attr('title')) {
                     var newTitle = obj.attr('title') + ' (' 
                                                + options.titleText + ')';
        } else {
                    var newTitle = options.titleText;
        };         
        obj.attr('title', newTitle);         
       };        

       obj.click(function(event) {
          event.preventDefault();  
       var newBlankWindow = window.open(obj.attr('href'), '_blank');
       newBlankWindow.focus();
     });     
       });    
  };  
 })(jQuery);

Example Usage

$('a[rel=external]').newWindow();

You can also change, or remove the title text, by passing in some JSON options

Example to change title text:

$('a[rel=external]').newWindow( { titleText: 'This is a new window link!' } );

Example to remove it alltogether

$('a[rel=external]').newWindow( { titleText: '' } );
alex
A: 

I use this...

$(function() {
  $("a:not([href^='"+window.location.hostname+"'])").click(function(){
    window.open(this.href);
    return false;
  }).attr("title", "Opens in a new window");
});
Mac