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):
1
2
3
4
5
6
7
8
// 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. via Why you shouldn’t use target=_blank, and what to use instead | Jalada.

Leave a comment


Scroll to Top