Using JavaScript instead of target to open new windows

Update: The technique described here is not ideal. Read why in New windows with JavaScript and the target attribute.

In my recent post about The target attribute and opening new windows, I stated that when I am faced with no other choice but to open a link in a new window, I prefer using unobtrusive JavaScript instead of the target attribute. The reason is that I always use a strict doctype, which does not allow the target attribute.

What I did not say was exactly how the script I use is constructed, but I guess I should have. A few people commenting on the post thought that I was suggesting the use of JavaScript to insert the invalid target attribute simply to hide it from the W3C Markup Validator. Cheating to pass validation is not what I am proposing.

After a bit of searching I wasn’t able to find a detailed description of this kind of script, so I thought I’d write one. It isn’t a very complicated script, so it’s hardly groundbreaking, but I hope somebody will find it useful.

For the script to work you need to edit your markup just a little, since the script needs to be able to tell which links it should affect. Some use the rel attribute for that, but I prefer using the class attribute since it allows me to style the links that will open a new window. The script looks for links with a class name of non-html, and allows multiple class names.

I think the class name non-html also serves as a good reminder that one of the few times it may be ok to make a link open a new window is when its target is a document in a non-HTML format. Common examples are PDF files and Word documents.

The user should always be warned when links will open new windows, so the script also adds a text with some information about the link’s behaviour. To make it stand out a bit more to people browsing with CSS off and JavaScript on, the text is wrapped in an em element.

Example markup:

  1. <a href="http://example.com/" class="non-html">The example.com website</a>

Try it out in the JavaScript target demo document.

To use the script, make sure these two functions are included in your common.js or wherever you store your global JavaScript functions:

  1. /*
  2. Create the new window
  3. */
  4. function openInNewWindow() {
  5. // Change "_blank" to something like "newWindow" to load all links in the same new window
  6. var newWindow = window.open(this.getAttribute('href'), '_blank');
  7. newWindow.focus();
  8. return false;
  9. }
  10. /*
  11. Add the openInNewWindow function to the onclick event of links with a class name of "non-html"
  12. */
  13. function getNewWindowLinks() {
  14. // Check that the browser is DOM compliant
  15. if (document.getElementById && document.createElement && document.appendChild) {
  16. // Change this to the text you want to use to alert the user that a new window will be opened
  17. var strNewWindowAlert = " (opens in a new window)";
  18. // Find all links
  19. var objWarningText;
  20. var strWarningText;
  21. var link;
  22. var links = document.getElementsByTagName('a');
  23. for (var i = 0; i < links.length; i++) {
  24. link = links[i];
  25. // Find all links with a class name of "non-html"
  26. if (/\bnon\-html\b/.exec(link.className)) {
  27. // Create an em element containing the new window warning text and insert it after the link text
  28. objWarningText = document.createElement("em");
  29. strWarningText = document.createTextNode(strNewWindowAlert);
  30. objWarningText.appendChild(strWarningText);
  31. link.appendChild(objWarningText);
  32. link.onclick = openInNewWindow;
  33. }
  34. }
  35. objWarningText = null;
  36. }
  37. }

Thanks to Robert Nyman for looking over the script for me and pointing out a couple of mistakes I’d made.

Either copy and paste from here or download my sample javascript-target.js file, which contains all the JavaScript you need to use this.

Be aware that if you use XHTML served as application/xhtml+xml, document.createElement() will not work in all browsers. In that case you should take a look at Simon Willison’s createElement() function, described in Javascript, the DOM and application/xhtml.

After that you need to make sure the getNewWindowLinks() function is executed when the document has loaded so it can insert the onclick event handlers. Use your favourite addEvent() function. There are many different addEvent() functions floating around, but the winner of PPK’s addEvent() recoding contest should be a good choice. Once you have an addEvent() function in your JavaScript library, the following will load the getNewWindowLinks() function.

  1. addEvent(window, 'load', getNewWindowLinks);

I suggest putting that line can be at the end of common.js.

So what are the benefits of opening new windows this way?

  • You can keep the strict doctype, which makes it easier to keep track of any presentational markup that sneaks its way into the markup.
  • The script is unobtrusive, meaning that for users with no JavaScript support links will open normally (in the same window).
  • People who use tabbed browsers can still choose to open the link in a new tab.
  • It doesn’t interfere with extensions like Tab Mix Plus that let Firefox be configured to open links that open new windows in a new tab instead. Update: It apparently does interfere with Tab Mix Plus under certain circumstances. See comment #1 on this page.

Of course this function could be extended to accept a whole lot of parameters like window size and such, but I’ve deliberatly kept it as simple as possible.

And again, don’t forget that opening new windows should generally be avoided.

Update: After considering the suggestions made in the comments I have made some changes to the script. Please use the updated script as described in Opening new windows with JavaScript, version 1.2 instead of this version.

Posted on May 2, 2006 in JavaScript

Comments

  1. I noticed that your demo script opens a new window - a tab actually - twice.

    I use Firefox with Tab Mix Plus extension. The second tab gets opened only when I have the “Force to open in new tab: Links to other sites” option on. When this option is disabled, only one new tab gets opened, as expected. It seems that the script actually does interfere with this extension and the action of opening of the new window is done twice. At least in this particular setting.

    But anyway: good work!

  2. I’m just curious, when do you actually need to open a new window?

  3. I find it amazing that it takes 38 lines of code to do what target=”_blank” did already and it even worked with JavaScript turned off. All this time I have been trying to use a minimum amount of code. Looks like I have been doing it wrong all along.

    I try to follow the W3C recommendations, but the removal of the target tag escapes me. I know it was meant to be used for frames, but opening a new window is a very practical use for it.

    Does anyone know the reasoning behind this or did I answer my own question with my frames comment?

  4. @ ErikHK, those very nice people called ‘Clients’ who request them.

    This is pretty similar to the script I use to open new windows when said people request them. The script I use is by Sitepoint called ‘New-Window Links in a Standards-Compliant World. This script uses the rel attribute, instead of classes.

    The script could be improved, such as adding a title attribute. In theory you could style links using the script with the attribute selector a[rel~=external] {} but we know who doesn’t support that. So, instead, use the script to add a class to the link, and denote the new window using that appropriate selector.

    I have had a few people saying that you’re only using JavaScript to bypass validation. And to this I now just laugh. I believe that opening new windows are behaviour, and this is exactly what JavaScript is indended for.

  5. May 2, 2006 by Roger Johansson (Author comment)

    Krzysztof: You’re right. I didn’t notice that because I never changed that particular setting in Tab Mix Plus. I wonder why it happens though…

    ErikHK: In extremely rare cases. Displaying an extensive help document or some kind of agreement when the user is filling in a form may be one such case. But the most common case of having to open a new window is when somebody in marketing has decided that all links to other sites must open in new windows, and the designer or developer simply has no say in the matter.

    Jeff: Yes, this is more complicated than using the target attribute. Look at it from the bright side though - it will make you think twice about opening new windows ;-).

    The target attribute has never existed in a strict doctype: Why was the target attribute removed from XHTML 1.1?

    A couple of good articles about why you should avoid opening new windows:

  6. May 2, 2006 by Jan Oberst

    I’m using Behaviour for this purpose.. The easiest way I know to add Javascript behaviours, and you can add them to every class/ID/element you’ve got. If you’re not that much into Javascript hacking you get an unobtrusive little script (~190 lines)…

  7. I think target was deprecated from strict doctypes primarily due it’s misuse (like blink) to insert behaviour into html pages ratehr than it’s intended frame usage. I have seen sites where virtually ever link has had target=_blank requireing a new window and the accompanying use of system resources. On a lower end system with limited memory available (or even a higher end one with multiple tasks going on) opening a bunch of extra windows can be a PITA at the very least - and if the client app leaks memory it compounds the problem.

    That said - it can be useful to open reference documents, larger image views, selected forms and a number of other things in a small temporary window from time to time.

    I agree that such is a “behaviour” and therefore the purvue of scripting, not markup. I think however, one should if possible let the site visitor know that clicking a particular link opens a new window. Part of the size of the above script is that functionality. If you put the notice on the page near the link itslef you could save a lot of “script space”.

  8. May 2, 2006 by Roger Johansson (Author comment)

    I think however, one should if possible let the site visitor know that clicking a particular link opens a new window. Part of the size of the above script is that functionality. If you put the notice on the page near the link itslef you could save a lot of “script space”.

    True, but that also means that the text will be displayed for everybody, including people with JavaScript turned off or unsupported. The point of using the script to display the warning text is to avoid confusion.

  9. I think the script would be more useful if the link itself remained normal, but the (new window) opened in a new window.

    Then possibly some additions so that it displays like (new window, PDF) for example, possibly with an image. It would probably at worst double the size of the script (the self-contained data-URI’s are for the sake of easy UserJS, of course).

  10. May 3, 2006 by Scott

    Excellent! I have been shamefully using inline Javascript in an onclick attribute to do this up until now because my Javascript knowledge was insufficient to figure out how to do it unobtrusively. I am sadly in one of those situations where people demand that certain things open in a new window and upper management forces me to comply.

  11. May 3, 2006 by Alex McKee

    Roger,

    I created a similar script sometime ago, and I agree with you. In my script, rel=”external” is used to denote a link that should be opened in a new window.

    What I particualy like about this is that behaviour is being abstracted to the scripting layer. It makes it easy to remove at a later date: take out the script and no more new windows.

    Best

    Alex

  12. Like Alex, I also made a similar script that uses the rel=”external” method of determining which links open in new windows. I actually went one step further on my own site and provided users with a way to turn it off as well, so nobody can complain about new windows if they don’t want them.

  13. Tab Mix Plus must be using similar method to open links in new tabs. Therefore two event handlers are attached and fired: yours and the one defined by the Tab Mix.

    I’m just guessing, but it may be the cause.

  14. class=”non-html” is not appropriate for this. We have the type attribute for exactly that purpose. You can use, for example: <a href=”foo.pdf” type=”application/pdf”>Foo (PDF)>/a<.

    Regardless of that, opening a new window for a PDF or any other format is wrong because you don’t know how the user has configured their browser and the external application. PDFs, for example, may load within the browser window, they may be saved to disk or they may launch an external application. Opening a new window for all but the first scenario will typically result in an new blank browser window.

    I know I’ve said this many times before, and I’m sure it’ll come up many more times in the future: There are no valid use cases for opening a new window!

  15. May 3, 2006 by Lachlan Hunt

    Oops, I take that comment back about no valid use cases for opening a new window. I’m pretty new at this web programming thing and have only created a few home pages and a myspace profile. So, I will hopefully discover more uses for this new window thingy later on.

    Edit: This comment was not posted by Lachlan Hunt but by somebody claiming to be him. Please don’t do this. /Roger

  16. You’re right Roger. This isn’t ground breaking. But I know it’s perfect for your audience and that’s mostly what counts.

    However as a JavaScript Developer, so many parts of me want to re-code the stuff you’ve posted in this entry. But it’s all good for now; it bought you some solid traffic for today :)

  17. Hi Roger,

    Personally I don’t understand why sites shouldn’t open some windows in a new browser. Personally I love browsing sites like cssbeauty and other kind of artsites. Whenever I click a link that goes to another site (or demopage like the one you have in your example), I always expect the sitebuilder to make it a link to another window. Not because it should be valid-code. But more because I think the backbutton is for use with links to another page of the same website.

    If I click a link that leads to another website, I often see things that interest me, and don’t want to click back.

    I believe that all information that is in regard to the website your browsing (like the example above: a pdf, or a piece or artwork, or even a css-listing site) should be opened in a new page. In example of the PDF, the PDF is an addition to the site you’re currently browsing. You watch the PDF, and go back to continue browsing the site itself. In that case I prefer to see and/or use a new window.

    In the case of site- or artgalleries we’re talking about sites with a lot of things to show. I want to see a new page (or Lightbox) to show that art or site. Clicking the backbutton for me is more obtrusive then to close a window. I wish to keep the site I’m browsing while looking at other stuff at the same time.

    The new windows also is a good reminder to the reader that they have a website in the background (or another tab) that they wanted to see.

  18. You start out with “I prefer using unobtrusive JavaScript instead of the target attribute. The reason is that I always use a strict doctype, which does not allow the target attribute.”

    And right after that you say “Cheating to pass validation is not what I am proposing.”

    I can’t see how you can not be cheating to pass validation in this case. You’re simulating the exact same behaviour that I assume was removed from the doctypes for a reason (obtrusive?).

    In my opinion, when popups are necessary, do them inline with the page. And if you have to use window.open() it is in fact OK on occasion. But please don’t say that it’s because “target doesn’t validate”, because then you seem to have failed to understand on of the reasons of why we bother validating or pages, and propose that anything that isn’t explicitly disallowed is OK to play.

    I wrote about this recently here: http://www.edea.se/FoolingtheValidator

  19. 2006-05-03, 4.37 by Lachlan Hunt Oops, I take that comment back about no valid use cases for opening a new window. So, I will hopefully discover more uses for this new window thingy later on.

    Lachlan, actually you are right on your first statement. So you do not need to comment back.

    There is NO valid use of opening a new window.

    Let us examine the so-called valid cases one by one:

    1. Use of frames: 99.99% times frames are evil and should be avoided.

    Frames are generally used to hold navigation part on a separate unit. Which is the wrong way to do it. The right way is to use server side includes.

    1. Opening and informative pop up, or a modal dialog. This can be done by using javascript and ajax and opening the pop up on the same page as a non-javascript fallback.

    Users are more intelligent then we think and they know how to use the back button

    They also get used to their user agents’ shortcuts (like shift-clicking to open a new window) more quickly than we assume.

    To sum up, user’s are not dumb-headed. And they really don’t like to be fooled.

    Cheers.

  20. I wonder why the strict definition prohibits the use of the target attribute. Is opening pop-up windows considered to be bad? I wonder what is the reason in the first place.

  21. function externalLinks()
    {
      if (!document.getElementsByTagName)
      {
        return;
      }
    
      // Get all anchors
      var anchors = document.getElementsByTagName("a");
      for (var i = 0; i
    
  22. I couldn’t paste the script. But i use a script that’s loads on startup and dom-element to add a target=”_bla”, updates the title and adds a class to al links with rel=”external”

    http://www.saspijkerman.com/includes/externallinks.js

    I wanted to paste the script in the last comment but it changed its layout / markup so i pasted a link in this comment

  23. @Alex McKee & S.A. Spijkerman

    Yeh, that’s just like the Sitepoint script I posted at number 4.

    @Chris, Roger posted two links to articles about opening new windows and why they are bad. Recommended reading.

    Everyone who said “there is no valid reason to open new windows”… maybe not, but there are clients (who pay money)

  24. May 3, 2006 by Roger Johansson (Author comment)

    Dustin: :-) You’re welcome to suggest improvements to the script.

    Joram: If you like having links open in new windows, you as a user have the power to tell your browser to open new windows. In most (all?) browsers you can bring up a contextual menu when clicking on a link and choose “Open in new window” or something similar. Problem solved.

    Raevel: This is not just meant to keep the document valid. It is also meant to move behaviour to the behaviour layer (scripting).

    Lachlan, volkan: In principle I agree with you. As a user I hate when sites open new windows. I think there are edge cases where it may be acceptable, but in general no.

    Chris: See the links I posted in comment 5.

  25. You have a point Roger, but I see links that open in a new window as something that a website(builder) does with a purpose. I do agree that if a website opens éverything in a new window, it becomes rather annoying.

    But links that open in a new window with a purpose (pdf’s, other sites, art and such), is usually widely accepted by the user. They know that because of that new window, they are watching something that the original website wants them to see, without instantly leaving their website. Not because the website(owner) doesn’t want to lose visitors, but because they see it as an extension to what they are providing the user with.

  26. As a user: I dislike opening of new windows so much that I’ve set my regular browser to suppress ‘target’ and block unwanted ‘pop-ups’. So, as a user the whole issue doesn’t matter all that much.

    As a web developer: I have yet to find good use for opening of new windows, but I guess there might be some border-cases. I will probably use a script like the one demonstrated here, if I ever find such a border-case and choose to go for opening of a new window.

  27. May 3, 2006 by Henrik

    The zealous discussions for/against opening a new window is a spitting image of the goto statement for/against. Eventually you become pragmatic and realise that what counts is what improves the final outcome in the eyes of the user.

    Personally I curse whenever a link away from the current site doesn’t open a new window.

    I’m glad you submitted the article, and even more happy about the comment reminding us about behaviours. I always wanted to look into using those.

  28. function externalLinks() { // does the browser support the DOM?

    if (!document.getElementsByTagName) { return; }

    // create an array of the anchors present in the document

    var anchors = document.getElementsByTagName(“a”);

    // loop through the anchor array

    for (var i=0; i

  29. May 3, 2006 by FlorentG

    * Roger said *

    If you like having links open in new windows, you as a user have the power to tell your browser to open new windows.

    Last week, I had a meeting with a customer. We are making for him a complete e-commerce site. On a product’s info page, there is the possibility to display a link to the manufacturer page. Ideal candidate for a new window.

    The customer asked me if this link opens in a new window, I said “yes it does”. But I also told him that he could also right click on it, and select “Open in a new window” (I wanted to see what he would answer to this, if I could remove this behavior and use a standard link which opens in the current window). He replied “okay okay”… But one of his employee then told me “Please think of the newbies, we don’t know how to open in a new window”.

    It showed me something : we, power users, know how to use a browser. Even if we open a link in the same window, and navigate 50 pages in the new site, we will know how to come back to the original site… But lots of users don’t. Lots of people, after clicking 3 times on the back button, may give up.

    We have to ask ourselves : Why is there the possibility of opening a site in a new window ? Why is it possible ? Why is it so bad to do it automatically ?

  30. Sorry - above code got garbled!

    function externalLinks() {
      // does the browser support the DOM?
    
      if (!document.getElementsByTagName) { return; }
    
      // create an array of the anchors present in the document
    
      var anchors = document.getElementsByTagName("a");
    
      // loop through the anchor array
    
      for (var i=0; i<anchors.length; i++) {
    
        // get various anchor properties
        var anchor   = anchors[i];
        var rel      = anchor.getAttribute("rel");
        var title    = anchor.getAttribute("title");
    
    
        // set the regexp to test for
        var external = /external/;
    
    
        // if the anchor has a href and a rel attribute containing the string 'external'
        if (anchor.getAttribute("href") && external.test(rel)) {
    
          // set the anchor target to blank
          anchor.target = "_blank";
    
          // append a helpful message to the title attribute
          anchor.title += " [opens in a new window]";
        }
      }
    }
    
  31. still garbled, but at least its understandable. sorry.

    (add rel=”external” to a link to invoke the pop-up behaviour.)

  32. Matt Wilcox - that’s just what I was going to suggest (ask for, really, since I ain’t no JS maven). Keep the code clean, and add the behavior when and where you need it. Brilliant!

  33. It showed me something : we, power users, know how to use a browser. Even if we open a link in the same window, and navigate 50 pages in the new site, we will know how to come back to the original site… But lots of users don’t. Lots of people, after clicking 3 times on the back button, may give up.

    Just the reason I was looking for FlorentG :) Of course it’s really great to think professionally, and to keep valid markup in mind. But most internetusers don’t even know how to properly use a website and a browser. There’s a reason why a lot of clients feel website prices are “ridiculously” high, since they don’t care (and don’t know about) valid markup. These people simply don’t know enough about the usage of browsers and might not know about using the backbutton, or the rightclick-option to open a new window ;-)

  34. May 3, 2006 by tripdragon

    Blah Blah Blah.. Sorry but this is just silly.. target_blank works fine.. If java is off it still works!

    As said above standards dont mean jack if your page stop working on that weird broswer..

    It’s just stufffffffffffffffffffff Standards are still just guidle lines

  35. DOCTYPEs should be set based on site requirements. What your doing is making a strict DOCTYPE behave like a transitional DOCTYPE. What a waste of time. Next you’ll be using JavaScript to use font tags validly in a strict DOCTYPE.

    Swallow your pride and use transitional.

  36. May 3, 2006 by Jim Miller

    About the class “non-html” being inappropriate, and the type attribute being the way to go:

    The primary problem I see with using “non-html” as a class name is that it doesn’t describe the content when you’re linking to a web site (as in the example), which dashes any hopes of creating semantic markup.

    Maybe having both “non-html” and “external-link” classes is the way to go? They could both be styled identically, and you could use one or the other to the same effect, or even use them together, in the case of linking to an external PDF document or whatever.

  37. I would love to see Dustin’s retooled version of the openInNewWindow() script. Dustin, I’ll be watching your site in anticipation of your version.

    In regards to Roger’s script not being “ground breaking”. I have no doubt this script will be adopted by the community; improved, trimmed and optimized. It’s all about planting the seed.

    So many times I have seen someone put a code snippet out there and watched as the community took it upon themselves to make the script the best it could be. I’m sure some day we’ll all be using the Johansson openInNewWindow() script in our global.js library.

    I can hear the Internet churning out code now…

  38. “Some use the rel attribute for that, but I prefer using the class attribute since it allows me to style the links that will open a new window.”

    Rel is more semantically relevent than a class for this purpose. Plus modern browsers can style based on the rel attribute anyway, using CSS3 (as I am in no doubt you’re aware):

    a[rel*=”external”] { color : red; }

    Though IE won’t understand that CSS.

  39. May 3, 2006 by FlorentG

    @Matt

    a[rel*=”external”] { color : red; } Though IE won’t understand that CSS.

    Fortunately, IE7 will understand this

  40. the behaviour of your script isn’t very unobtrusive when trying to open the link in a new tab using ctrl+click. I’d recommend not changing the default behaviour when ctrl, alt, or shift are pressed. Here’s some code to do just that:

    function openInNewWindow(e) {
      if(e.shiftKey || e.ctrlKey || e.altKey) return;
    

    @Matt

    a[rel*=”external”] { color : red; }

    Somethis like this will however have a very strange result when JS is disabled.

  41. May 3, 2006 by DaveMo

    Oy! Am I SOOOO confused!

    Just when I think I’ve got it figured out and coded appropriately, WHAM!, someone depreciates an attribute on me! I did not know this until just now!

    Okay, so I’ve been using the target=’_blank’ attribute to open non-HTML documents like PDFs, Word and Excel files on our site (as propounded by Jakob Nielsen) and also when a link leads off our site, both of which seem like good and logical usability practices. I use the ‘TITLE’ attribute to indicate and inform the user of the impending action as well whenever I possibly can as well.

    But I appreciate the goal of this concept and agree in attempting to adopt it in practice ( Although, people who know the situation I deal with here at work will realize what a futile effort it would be ), or at least until after I understand the whole issue better and more confidently.

    However, is there a way in all this JavaScripting and DOM manipulation to bring the user’s choice more to the forefront?

    What I’m asking is, would it be possible, or even be considered best practice, to have a dialog box appear after clicking the link that presents the user with the choice of opening in a new window or not? Perhaps something that said ‘Would you like to open this link in a new window/tab?’ ‘Yes/No/Cancel’ or, ‘New/Same/Cancel’.

    I’m not very knowledgeable on the finer points of JavaScripting or DOM behaviors to know if this is even possible, so I put this out there to those of you that are to enlighten me as to the feasibility of this idea.

    As always, I appreciate the time and effort everyone puts into these forums and I use the knowledge I glean from them to improve my skills and code!

    Thanks!

  42. I seem to agree with ryan. I mean really look ,at the difference between Transitional and Strict (Allow pause for you to do so)… great now realize while your script achives its goal, the effort/time invested and length of the script suffocate pride. All you had to do was change your DOCTYPE, watch the site develop into the same visual output and move on. You could have logged some serious Tetris DS time in…

  43. May 3, 2006 by mattw

    What about just doing this:

    a href=”http://www.microsoft.com/” onclick=”window.open(this.href); return false”>

  44. May 3, 2006 by Christian

    Ok, both sides have made their cases. On one side, it’s bad to open in new windows with target=_blank due to th fact that it doesn’t validate on strict and it’s not up the the user to decide how he/she wants to browse the link. On the other side … most of the users don’t really care. They might even wonder why the link didn’t open in a new window and maybe they even don’t know how to open it in a new window/tab.

    And how about the CSS3 specification-draft? There is a property (target-new) that can be set to open a link in a new tab or window. Will it then be ok to open it in a new window because is standardcomplient?

  45. May 3, 2006 by Ajax Shrugged

    Opening and informative pop up, or a modal dialog. This can be done by using javascript and ajax and opening the pop up on the same page as a non-javascript fallback.

    You have GOT to be kidding. Dear God, tell me you’re kidding.

    How am I supposed to arrange the informative pop-up next to the main page’s window if it is embedded in the document and can’t be moved outside the window? How am I supposed to Alt-Tab between the two? Sure you could write JavaScript for some of that functionality, and all the other ways users might want to manipulate the faux window, but the user’s computer already has a perfectly functional window manager that he already knows how to do those things in (or doesn’t know, in which case he certainly isn’t going to learn your way either). Why reinvent the wheel?

    You’re putting the cart before the horse, cutting off your nose to spite your face, and committing several other cliches here. Not being able to use the TARGET attribute because you’re using a strict XHTML doctype is a reason not to use a strict XHTML doctype. It is not a reason to write a 38-line JavaScript to get around the fact that you can’t use TARGET. Or you could just live with the fact that your page doesn’t validate 100%; there’s this thing browsers do called “graceful degradation.” If a browser doesn’t know what to do with TARGET, then it will ignore the attribute entirely. There is no way having TARGET in your A tags is going to mess up your layout even if you’re claiming strict XHTML 1.1 in the DOCTYPE.

    Now you may want to use JavaScript to open pop-up windows for the control it offers over e.g. window size and chrome. In this case you DO WANT to use TARGET=”_blank” so your page will at least approximate the desired functionality on browsers without JavaScript!

    I mean, please, common sense. The Web 1.0 way of doing things works perfectly well for many purposes, not everything has to be Ajaxified to the extent that people can’t even follow what you’re doing when they view source.

  46. May 3, 2006 by Roger Johansson (Author comment)

    Joram: The opinions on whether or not you should open links to documents in a non-html format vary. If you decide to do so, make the user aware of it so they can take appropriate action if they do not want a new window to open.

    Matt: Yeah that will also work, but I think the new window warning should be more obvious than hidden away in the title attribute.

    FlorentG: I take it you have never seen usability testing where people get incredible confused by new windows. Many novice users don’t even realise than a new window has opened.

    Ryan: So stick with your transitional doctype if it makes you feel better. I prefer triggering full standards mode in all browsers and being able to use the validator to check for presentational markup.

    Jim: Yeah the class name is a bad choice for the link in the example. Your suggestion of multiple class names seems reasonable.

    Matt: Yeah using the rel attribute would work for modern browsers and IE7, but as gerben points out in comment #40 that would confuse people with JS off/CSS on.

    gerben: You’re right. Thanks for pointing it out, I’ll look into adding a check for that to the script.

    DaveMo: Giving the user a choice is the best solution in my opinion. Using a dialog box seems a bit too intrusive though. Maybe you could provide a site-wide setting or something, or display the choice right next to the links.

    Robs: See my response to Ryan.

    mattw: Nope, because I don’t want to use inline javascript.

  47. I must be invisible. sigh :(

  48. May 4, 2006 by FlorentG

    Roger Said :

    I take it you have never seen usability testing where people get incredible confused by new windows. Many novice users don’t even realise than a new window has opened.

    I have read some usability reports, and lots of articles :) This includes Jakob Nielsen useit.com famous articles.

    But, in response to those testings, I have a question : for how long will a novice be confused by new windows ? Windows are everywhere, it is a key component of our everyday operating systems… If he’s confused by a browser, what about other softwares ? And is he confused everytime ? Or just the 2-3 first times ?

    I may be wrong, but I think that a novice who doesn’t notice a new window doesn’t know about right-click’s Open in new window option.

    I even had a live example. A friend of mine, complete novice, wanted to search something. He went on google, typed some stuff. He then clicked on the first result. The link opened in the same window. He navigated through several pages, and we he had done, he asked me “Hey ? Where’s Google gone ?”.

    What I want to say here is that I think that opening new windows or not is not a web page usability problem. It is a web browser usability problem.

    Some developpers are afraid that the surfer will not go back to their site. Maybe because it is difficult to go back to a site. There are lots and lots of article on the web speaking about “organizating navigation in your site”. But there’s nothing for “organizating navigation between sites”… Why don’t I have a “previous site” button in my browser ? It would solve lots of problems I think…

  49. I’m more of a “rel” fan myself, and while your looping through them you can add a class to style them as well.

  50. I have two other reasons for opening new browser windows. First is for sites that are always session-based with a timeout if inactive for some time. For example this is the case of the Internetbanks I work with and often we have to provide theese visitors with links to other sites. But we absolutely don´t want theese visitors to leave the site without logging out because of security-reasons.

    Theese sites are also ssl-secured and here comes another reason why a new window is apropriate. If you don´t open the link in a new browserwindow the user (depending on browser settings) can face a warning message that he is leaving the secure site. Even though the message should be of help, novice users tend to feel more insecure when faced to theese messages. At least that is my experience.

  51. May 4, 2006 by Anonymous

    Blah Blah Blah.. Sorry but this is just silly.. target_blank works fine..

    Sure? How about mobile devices, non-textual linux terminals (lynx), Are you sure it does not lead any accessibility issues with exceptionals who have motor disabilities. Do you think visually impaires, like to track pop ups jumping ubiquitously all around?

    If java is off it still works!

    Java is not javascript. I assume it’s just a typo you made.

    As said above standards dont mean jack if your page stop working on that weird broswer..

    If constructed properly your page will not stop working in any browser. It will just degrade gracefully.

    It’s just stufffffffffffffffffffff

    (TODO:// add more f’s here)

    Standards are still just guidle lines

    Standards are more than guidelines, they are said to be “recommendations” but they are more than that.

    People are tirelessly putting years’ thought and effort on them, considering any single possibility including present and the future.

    Standards are a way to ensure that what you design will behave as expected in any standard-supporting agent.

    Assume IE magically decides to remove all deprecated attributes including target. (I am 99% sure they won’t) If you are adhering standards, then you will not need to change any single line of code and markup.

    I believe standards should be adhared at all costs, since you cannot create globally acceptable standards for yourself.

  52. May 4, 2006 by FlorentG

    Sure? How about mobile devices, non-textual linux terminals (lynx)

    I think this is why target was removed from Strict DTDs. The behavior of links may depend of the media.

    But guess what ? There’s a target property in the CSS3 Hyperlink module working draft ! When CSS3 will be fully implemented, we will have the oportunity to open links in the current window, in a new tab (yes, tab), or in a new window, depending of the media. And because it is CSS, advanced users will be able to override everything thanks to custom CSS and the !important directive.

    Do you think visually impaires, like to track pop ups jumping ubiquitously all around?

    Sure. But at least Jaws screams “New Windows” when a new window is opened :)

  53. May 4, 2006 by Michaël Guitton

    Here’s an enhanced version. If window.open call ever fails, it allows the hyperlink to be followed by returning true. Please note that config variable could be made a closure (this would improve the usefulness of this code snippet)

     1. function openInNewWindow()
     2. {
     3.    var config = {
     4.       status: 1
     5.      ,resizable: 1
     6.      ,scrollbars: 0
     7.      ,width: 400
     8.      ,height: 400
     9.      ,target: '_blank'
    10.      };
    11.   
    12.   var attrs = '';
    13.   var sep = '';
    14.   for (var i in config) {
    15.     if (i == 'target') { continue; }
    16.      attrs += sep + i + '=' + config[i];
    17.      sep = ',';
    18.   }
    19.
    20.   var pop = window.open(this.href, config.target, attrs);
    21.   if (pop) {
    22.      if (pop.focus) { pop.focus(); }
    23.      return false;
    24.   }
    25.   
    26.   return true;
    27. }
    
  54. Ryan: So stick with your transitional doctype if it makes you feel better.

    It’s not my Transitional DOCTYPE, but it does make me feel better.

    I prefer triggering full standards mode in all browsers and being able to use the validator to check for presentational markup.

    A sound enough argument. But why don’t you set your own attributes, make your own doctype. It’s even more work, so it should make you feel even prouder of your accomplishments. Cus let me tell you the only thing the validator is validating in your scenario is your excuse to not make it the fast efficient way. When clients have mandates for a spectrum of browser types, your options are a little more limited then your garden of JavaScript delights.

  55. May 4, 2006 by kristian marinkovic

    if you use behaviour.js and cssquery.js (or any other getElementBySelector script) can use something like that:

    add the window script to all links that contain a “target” class

    "a[class~=target]" : function(el) {
    el.onclick=function() {
       window.open(this.href,     'Dokument').focus();
       return false;
    }
    }
    

    you dont have to code the loop yourself :)

  56. May 4, 2006 by Michaël Guitton

    Like Thickbox, this Prototype-based utility allows you to open windows within an HTML page. Dunno if it’s the way to go though since I fear it might be used to clutter your window space (thinking of ads…) :-/

  57. Why don’t I have a “previous site” button in my browser ? It would solve lots of problems I think…

    Some browsers (e.g. Opera) do have that, or something similar (e.g. “snapback” in Safari).

  58. What about using the rel attribute with the value of “external” or in this case “non-html” instead of class? I think it’s more appropriate.

    Then in future it will be upwards compatible to CSS 3:

    a[rel~=”external”] { target-new: tab; }

  59. I think this is a nice article which give you a diffrent point of view :)

  60. I think Thierry Koblentz solution has some advantages over your solution. I doesn’t need any changes to the markup and just one rule to your style sheet. http://www.tjkdesign.com/articles/popup_window_with_no_extra_markup.asp

  61. Hi, how to capture the unload event in safari browser using javascript, that is before closing the window. I tried with different ways, but i did’nt get that event. So please help me on this. Thanx.

  62. I hope this hasn’t been pointed out allready, and that someone will find this usefull - I believe that if it HAS to be done, it should be done with pure js, not by inserting invalid html…

    this is an example I wrote just today (before I realized that people had done it before me) http://users.skumleren.net/cers/examples/external_link.html

    it’s an unobtrusive javascript that (for testing purposes is written in the document, but could just as well be sourced in, and) will look through all anchors, and makes all links that has a href that starts with ‘http’ or ‘ftp’ (can easily be extended) open in a new window via javascript… no ned to alter any html inside the document…

    moreover, it takes into account the ‘feature’ of certain browsers, wheer getAttribute(‘href’) returns the resolved value of href, not the given value - this means that ALL links would start with http…

    It’s been tested to work in firefox, konqueror, opera and internet explorer

  63. July 6, 2006 by Ken

    OK, metaphysical arguements over whether or not you like seeing new windows pop open, like to write 2 pages of javascript to embed a popup dialogue window within your browser as if it’s better than using one line of javascript to do the same with a new browser window, or whether or not you can assume your audience has a clue and if you can ignore the lowest common user of your site to please the few that think the same as you …. is irrelevant and a waste of time.

    Here’s a real problem I havent seen addressed:

    Using IE7 beta 3, When I pop open a new window with window.open(…..) the new window loads fine, but the window from whence it came reloads with nothing but “[object]” when it should not be changing at all when you click the link. I’ve seen this since IE7 Beta 1, but I can’t find anything to fix it.

  64. December 1, 2006 by Mahendran

    Sir ,

    We Are Using Asp.Net & C# So Using Client Side Validation Javascript Here In alert Is showing Ok,Cancel Button Instead I Need The Yes,No Button Help Me

  65. December 21, 2006 by Stephen

    This guy at Sitepoint seems to disagree with this article:

    http://www.sitepoint.com/article/standards-compliant-world

    His reasoning makes sense. Yes, it’s not part of HTML anymore so you shouldn’t use the HTML attribute, but it’s still part of the DOM and there is no reason you shouldn’t be able to use Javascript to set the target attribute.

  66. January 6, 2007 by Asif Shakir

    I think its pretty irresponsible for W3C to deprecate the target tag especially when all browsers already support it. There is something called Backward-Compatibility hope the standards organization looks it up.

    Frames (IFRAMES) are useful in several situations like handling Master - Detail screens (Order + Order Items). I would even prefer loading a Date or Color selector in an IFRAME rather than a new window to avoid the entire rigmarole of popup blockers.

    Its not possible in many cases to do everything inline, especially if you are using content from other websites. eg. A frame to add functionality from a partner website.

  67. January 31, 2007 by Ctrl+Alt+Del

    We have some PDF format forms on our Intranet. I need to place a hyperlink in one of these forms, so that the hyperlink opens in a new browser window. Otherwise, when they back-button back to the form, the exiting form field entries are blank again. I have been looking in Acrobat and online, trying to find a solution - javascript or otherwise - to get this working, and you’d think I was trying to find the cure for cancer or something. This should NOT be this difficult. Or probably I am just a newbie moron. But anyway, any help would be GREATLY appreciated.

  68. February 1, 2007 by Ctrl+Alt+Del

    I found the solution:

    In your PDF document, create a javascript link with the following:

    app.launchURL(‘http://www.yourwebsite.com’, true);

  69. February 3, 2007 by Ctrl+Alt+Del

    Note: The java link above worked for my users with Adobe Std. 7.0 and Reader 7.0. It did not work for the Adobe Std. 6.0 users, and I don’t have anyone using older versions of Reader, so I couldn’t test that.

  70. But what about opening NAMED windows? (Proliferating ‘_blanks’ on my desktop drive me away from a site very quickly…)

    Instead I was wanting to open all external links in a SINGLE secondary named window, keeping my visitors on-site…

    The following works much as the others - I like the way switching javascript off simply disables the pop-up while not breaking things

    // NOT thoroughly tested...
    
    // set external links target
    
    var TARGET = '_blank'; // 'external';
    
    function init() {
    
     var local = window.location.host + ':';
     local = local.substring(0, local.indexOf(':'));
    
     for (var i = 0, n = document.links.length; i < n; i++) {
      var link = document.links[i];
    
      var remote = link.host + ':'; // ie6 adds ':80'
      remote = remote.substring(0, remote.indexOf(':'));
    
      if (local == remote) continue; // local
      if (!remote)         continue; // javascript:...
    
      link.onclick = function() {
       var w = window.open(this, TARGET);
       w.focus();
       return false;
      };
     }
    }
    window.addEventListener ? 
    window.addEventListener('load', init, 
    false) : window.attachEvent ? 
    window.attachEvent('onload', init) :     
    null;
    

    Anyone found a workaround for IE6’s infuriating “allow sub-frames to navigate across domains?” prompt when setting TARGET to anything other than “_blank”?

    Maybe best simply not to open new windows huh?

  71. I see no license information with your JS file you posted here, but I figured since you posted it, it is at least available for personal use.

    I’m interested in packaging it with a module for Drupal, so let me know if that’s alright.

    In doing this, I wanted to use your script without it adding text next to external links. In passing an empty string to the init function, it still creates an EM tag. I think an if statement should be added encapsulating lines 17-20 like the following:

    if(strWarning.length > 0){
      oWarning = document.createElement("em");
      oWarning.appendChild(document.createTextNode(strWarning));
      oLink.appendChild(oWarning);
    }
    
  72. February 24, 2007 by Roger Johansson (Author comment)

    Bryant: Yes, use it as you wish, though being given credit is always appreciated. Please use the updated script: Opening new windows with JavaScript, version 1.2.

    About not displaying the warning text… perhaps there should be a check for an empty string. But on the other hand, I really believe that you should never ever open a new window without explicitly making the user aware of it. I’d be more inclined to make a check that displays the default warning text if an empty string is passed in.

  73. May 2, 2007 by Alonso Álvarez de Araya

    Thank you very much for your script it saved my code! the empty line works perfect. Now I’ll look for an equivalent in php. Zanx a lot.

  74. June 25, 2007 by Lucy

    when we right click on the thing we want open a new window on it does a funny sound so we cant open a new window we dont know whats wronge with our computer can you please help us thank you.

Comments are disabled for this post (read why), but if you have spotted an error or have additional info that you think should be in this post, feel free to contact me.