Why you shouldn’t use target=_blank, and what to use instead

Update: It’s been pointed out to me (by x5315) that HTML5 didn’t actually deprecate the target attribute, so this is largely irrelevant; although it’s removed from XHTML 1.1, the ‘data-‘ style attributes are HTML5, not XHTML. The only advantage is that people who disable Javascript also wont get ‘annoying’ new windows popping up.

Adding target="_blank" to links in HTML has been the de facto method of opening links in new windows. But you won’t be able to one day because it has been deprecated as of XHTML 1.0 Strict and XHTML 1.1. Plenty of people will tell you you must never open new windows because it’s insulting to your users (they’ll open a new window if they want to) and it breaks the back button because the new tab/window doesn’t retain your browsing history.

But sometimes you just need to open a new window. So what’s the solution? Here’s my nifty method that utilises HTML5 custom non-visible data attributes and some unobtrusive JavaScript (with jQuery):

// Wait for the document to become ready
$(function() {
	$("a[data-popup]").live('click', function(e) {
		window.open($(this)[0].href);
		// Prevent the link from actually being followed
		e.preventDefault();
	});
});

That was easy! But how do you use it?

Instead of target="_blank" add data-popup="true" to your link tags. That bit of Javascript will find these links (and any new ones you insert into the DOM thanks to live bindings) and make clicking them open in a new window.

Not only that, but it will degrade gracefully with Javascript disabled because the href is still in the link tag. Plus, because it’s ‘unobtrusive’ you haven’t got Javascript onclick handlers littering your HTML and you’re not even adding pointless classes to your links.

I use jQuery all the time but could anyone factor out jQuery for me and provide a version of those 4 lines in vanilla Javascript? Or is it too much once you take into account live bindings and cross-browser support? Or do you have a better solution altogether? Let me know in the comments.

This entry was posted in Blog. Bookmark the permalink.
  • You answered your own question: just don’t open new windows. No, your reason isn’t good enough. Spawning windows is plain rude. There are about as many good reasons to make your software rude as there are to punch another person in the face—i.e., very very few, and yours isn’t one of them.

    As a general rule, if you’re starting a blog post with “this is a bad idea, BUT”, it’s probably a bad idea. 8)

    • OK my main argument is this. Twitterfall.com is a web app where leaving the page and coming back to the page causes everything to reload and reset. If someone clicks a URL in a tweet they are almost always going to want to open it in a new window.

      Imagine if your Twitter desktop client replaced itself with a browser every time you clicked on a link. Not very intuitive.

      In most other cases, I agree.

      • Isn’t that more a bug with Twitterfall, then? Make creative use of pushState so it doesn’t start from scratch when you navigate back to it. (Try browsing through a directory tree on github to see this in action.) Fall back to hash junk for pre-HTML5 browsers.

        Breaking the Back button isn’t a good reason to break even more things.

        • I’ll be sure to report the bug to the Google team 🙂 They better get working to replace all behaviour across all their apps.

          I knew you were going to say that though. It would probably be localStorage rather than pushState. But I don’t know how you expect me to be able to store up to 200 tweets (the ones displayed when the user left) in a URL string.

          I know where you’re coming from. But it’s a lot easier to be against it in theory than practice when it’s something like a web app.

          • You may be shocked to hear that I don’t use most Google apps 8)

            Admittedly URLs may not be the right thing here. But it looks like Twitterfall already remembers some of its state when I visiting again later; stash the current list of tweets (whether entirely or just by id) and show them again on load, and you’re done. That even seems like a good idea in general, just to give a returning user something to look at initially besides an empty void.

    • maclonghorn

      yes you do open new windows….you want your site to be sticky, so if you provide links to other, external sites, open a new window so the client doesn’t leave your site. that’s what tabbed browsing is all about. “back” in the browser is a pain.

      • “So the client doesn’t leave your site” sounds like something marketing would say, yes. Shockingly, when I (a real live human being, not “the client”) click a link, it’s because I’m done with your site and want to go somewhere else! I don’t need a damn trail of tabs showing every link I clicked so some CEO can dance with glee that I might accidentally see his site again and decide to buy something.

        • It really depends on the context. There are plenty of reasons to do it one way or the other, depending on the site. Many users are not knowledgeable enough to open links in a new window. As a user, I personally prefer when sites (especially Facebook, Twitter, Youtube, etc) open external links in new windows, because I am often not done browsing the site when I click the link (and of course) the external link does not contain any navigation back to the originating site.

          • It comes down to this:

            If a link opens a new window, but I didn’t want it to, I can’t do anything about it (and often may not know it’s going to spawn a window anyway).

            If a link doesn’t open a new window, but I want it to, I can make it do so.

            Err on the side that gives me control over my own window manager, please.

          • Indeed!

          • How about for an app? Specifically, a chat. It’s a lot easier if the chat opens in a small popup, then you can give support while keeping the relevant page open. That’s what I need.

          • Opera treats right-clicking the link and clicking Open as mandatory same tab (versus left-clicking for, what the link prefers, and middle-clicking or right-clicking and clicking Open in New Tab as opening in a new tab). Nice for that.

          • hurensohn

            You say it’s insulting to the user, well, what if you’re writing a Newsletter and you don’t want a link to close the email client…?

            It need to be open in a new window/tab. You’re insulting developers by suggesting we don’t know when a user is likely to want the link in a new window.

          • Yeah, good luck with that Eevee. The context of rude is based on the browser experiences common back in the ie 3.01b days and itself deprecated.

            It is what it is, and it isn’t what it once was. Browsing habits have changed significantly from over a decade ago and so have the preferences of *most* users.

            Being in the minority sucks, I know, but as such, it is what it is.

        • pugilist

          Well, aren’t you clever.

          Good enough reason for a new tab: I have site to go with my teaching so want external sites in new tabs while retaining the tab with the lesson notes / instructions that was being read.

        • jakee308

          I click on links all the time fully desiring to want to return where I was when I clicked. You’re making assumptions about other people’s habits based on your own. I think most folks have learned that if you leave a page when clicking on a link, when you return via back button, you may or may not be returned to the point in the document where you started from. You also will have to wait for the page to reload. while if you use a new tab, all you have to do is close that tab and you’re back where you were. Now some browsers don’t make this easy. I.E I think doesn’t but I don’t use it often enough to remember. I use firefox where a middle button click gets me a new tab for a link. Easy peasy. I’m surprised that HTML5 has deprecated the NAME attribute as how do you give the user a html tag free line of text to click on. One that’s usually explanatory. they say use the ID instead but the ID attribute I don’t believe gets shown as an alias. Whatever, I’m going to continue to use HTML 4.01 until I can’t. Maybe by then they’ll have corrected some of their assumptions. Originally, there was going to be XHTML and not HTML5 but I think they realized that was going to be a nightmare. Too restrictive and wouldn’t be adopted. They still went to far in my opinion.

  • Ookikoi

    why not use ‘ target=”data-popup” ‘ and select with $(“a[target=data-popup]”), that way it will open in a new window in more scenarios….

    • This post was written under the assumption that the ‘target’ attribute was being deprecated in HTML5, but it wasn’t.

      If you’re going to use target, just use target=”_blank”.

      • Ookikoi

        Well the idea was that in previous post, people would use an attribute, like
        data-popup=”true”, which is doubling the work… all I’m saying is, why not use the real attribute name, “target”, instead of one that means nothing. That way, when the browser does support “target”, it’ll use the native target behaviour, and when it doesn’t, you can bind your custom event with the jq selector
        a[target=data-popup]. data-popup not being a defined iframe/window, it’ll act as _blank, but indeed, use target=”_blank” would be the same
        . My focus was on he attribute name, not its value, and to use the native attribute name, target, rather than yet-another-attr-name-for-an-existing-behaviour
        🙂

        • That’s fine, but if we’re being technical my point is /if/ the ‘target’ attribute was deprecated in HTML5, it would be invalid markup to use it, whereas data- attributes are valid HTML5.

          So yes, your idea works perfectly and is simpler, but pedantically would be incorrect (under the post’s initial assumption which is wrong)

          • QnA

            doesn’t HTML5 allow for crappy/incorrect code?

  • Anonymous

    As opposed to responding to the click event of those links, I think it’d be cleaner to just dynamically add the target attribute, like this:

    $(function(){
    $(“a[data-popup]”).attr(‘target’, ‘_blank’);
    });

  • lozandier

    Not criticizing your code at all, but wouldn’t have using jquery’s .data() method been a whole lot faster to collect anything with the data attribute?  

    You could have made a data-href or data-new-link and then called it via $(this).data(‘href) or $(this).(newLink) [(Note: data ignores ‘-‘ after the frist one after ‘data’ and camel cases it). ] 

    • But then it wouldn’t degrade for people with Javascript disabled, right?

      • lozandier

        From what I understand; that may be the case if you don’t provide anything as traditional href for them to be able to access the new material for javascript.

        Thanks for helping me broaden my thinking with your contribution.

  • kotuwa

    how can we get colored text to display a code as we seen it in our code editors?
    Just like the code in this page…
    I mean in code editors we see different tags in different colors. How to make a document with those colored text. (without taking screenshots)

  • Brant

    As a seasoned developer, I sit here wondering if we have considered the audience, out users. Most GENERAL users do not know how to open another window from a link. I have read how this is rude but how is it, REALLY, rude? If you’re on a site that references another site why would you NOT want to open another window or tab besides history for the user?

  • JC

    I find it sort of humorous that folks are characterizing new windows as “rude” and “insulting”… the equivalent of “punching someone in the face”. Exaggerate a bit much?

    I’ll certainly concede that for experienced folks using a web browser, it is practically second nature to use “Open in New Tab” when we don’t want to navigate from our current page. But I find that, quite often, I would PREFER that links open in new tabs… even in instances where the link isn’t a PDF document or an entirely new site. If I’m in the middle of reading an article, but want to remember to follow-up on a link in the middle of the piece, I’ll open it in a new window so its waiting for me once I’ve finished reading the article.

    Back when using “_blank” as the link target USED TO open entirely new windows, I would agree that it was somewhat annoying on occasion. But with tabbed browsing having become something of a universal standard now, it’s simply not nearly as disruptive as it once was. What used to propagate a new window simply opens a new tab nowadays (in most newer browsers, that is). This behavior is much more desirable over old method of having a link create an entirely new window.

    Furthermore, most of the folks that are viciously arguing that “users know how to open in a new tab” and that they “don’t need the website to dictate that to them”, forget that they are speaking from the viewpoint of a particularly computer-literate person. While the Internet is used by everyone, ages 8 to 80, that doesn’t mean that all of these users possess a thorough understanding of the ins and outs of how to most effectively use a web browser. For example, I think of watching my mother use the internet. She browses websites on a daily basis, using the internet for all sorts of things… but I can pretty much guarantee you that if I asked her to “open that link in a new tab”, she would have no idea how to do so. And, in truth, that phenomenon is not just limited to the 50 and over crowd. Many fairly young people, while being exceptionally familiar with the idea of using the web, will go years and years without really exploring the full functionality of their web browser.

  • Gian Uberto Lauri

    I thin it could fail when the page is visited with a tablet (i.e. iPad) due the popup-blocking code.

  • Tom

    How about just:

    $(document).on(“click”, “a[target=_blank]”, function(e){
    e.preventDefault();
    window.open($(this).attr(‘href’), ‘_blank’);
    });

  • Andrew Leighton

    I disagree with this, nowadays a lot of users go in for tabbed browsing so opening a new page makes sense.
    On a personal note, there is nothing I dislike more than a link that takes you away from the main site into somewhere else. I just don’t think modern surfing habits work that way, Ebay, Amazon, Facebook, Twitter etc all use links that open up new windows, keeping the user on the main site. Not opening a new window, forcing the user onto a new site, making the user hit the back button to get back to where they were, then not being on the right spot on the page is just something from the 90’s.

  • That is absolute wrong i think, Target=”_blank” is a great attribute and i am using it with every external link with rel =”externa, nofollow”. I Think my Site Rocks.

    • THE MASKED UNIT

      i think your site sucks fucking dick

  • Rasmus Schultz

    > you must never open new windows because it’s insulting to your users

    So navigating away from, say, a radio-station or a single-page application, by default, is… less insulting? huh?

    > they’ll open a new window if they want to

    And if they remember to do so, and if they even know how to – plenty of users don’t. But we should punish them by interrupting their radio stations or letting them abruptly lose all their work in a single-page application. Definitely. NOT.

  • Jason Napolitano

    I do believe that this is dependent on two things.

    One; what type of link is it? Web developers should know which types of links the users will want to open in new windows. Certain links will not need to be opened in a new window, and any web developer with a bit of experience should be able to determine if a link is ‘important enough’ to open a new tab/window.

    Letting the user decide is not bad, which leads into reason two; Is that this method should only be used when needed and not to be abused. Sometimes, it is annoying when a ton of links open in new tabs, cluttering your browser and all from one site. However, let’s say your website has social accounts (Facebook, Twitter, Etc) and you want to link to your social accounts.

    If you ‘let’ the user choose how they want to open those links, the common user will not ‘middle mouse’ the link to open it, or right click and open in a new tab/window, etc. They will simply click the link. The problem with that and social networks, or links to external sites of popularity is that the user is likely to get distracted on this ‘new’ website they’ve found through your link and not even give your site a second thought. Therefor you just lost viewers/potential clients. Always remember, your users are not ‘always’ going to know how to operate their web browser. Most of them just want to click and browse.

    When thinking of this from a developer perspective, I truly believe it is very important to also view this from an SEO and a Sales perspective. You want to keep people on your site, looking at as many pages as possible for as long as possible. And if you encourage a visitor leave your site, you might have just lot a sale.

    Just my two cents. Using the “_blank” is not bad, if used correctly. But I have been using and watching people of all experience levels use the internet for some years now and have been developing websites for some years as well. And this is the common practice, and this is my method: Let the links be natural and use the “_blank” when strictly needed. It accommodates both margins, by enforcing ‘specific’ links to open to a new window/tab and the rest open in the same one.

  • Eddieb
  • I don’t know script so I can’t comment on that, but about being rude?!

    I couldn’t disagree more. As a user I am do not find it rude. In fact I like the new window and not having to hit the back button, which in some cases can screw up the original page you were on.

    As a site owner I love. Who wants someone to click on an ad only to completely leave your site?