Coding with Jesse

target="_blank" With XHTML 1.1

January 24th, 2007

I received a question this morning from someone asking:

In XHTML 1.1 we cannot use attribute 'target=blank', so what is the solution?

The solution is to use regular links, but to make them open into a new window using JavaScript. To do this, we can add something to the links to flag them as being special, perhaps a class called new-window:

<a href="page.html" class="new-window">Page</a>

Then, use JavaScript to find all the links that have this class name and tell them to open in a new window:

window.onload = function() {
    var links = document.getElementsByTagName('a');
    for (var i=0;i < links.length;i++) {
        if (links[i].className == 'new-window') {
            links[i].onclick = function() {
                window.open(this.href);
                return false;
            };
        }
    }
};

or using jQuery:

$(function(){
    $('a.new-window').click(function(){
        window.open(this.href);
        return false;
    });
});

If you have any other questions like this, feel free to ask me and I'll be happy to answer them here.


Comments

1 . Martin S. on January 24th, 2007

Martin S.

If you really do want to open new windows, shouldn't you consider using another doctype, for instance a transitional one, which does not require you to not open external links with the target attribute?

Nice code anyway. :)

2 . Jesse Skinner on January 24th, 2007

Jesse Skinner

Sure, you could use XHTML 1.0 Transitional. But if you want to use XHTML 1.1 and have links open in a new window, you're stuck using JavaScript to do this.

3 . trovster on January 24th, 2007

trovster

This is exactly the same solution which was posted in a sitepoint article titled New-Window Links in a Standards-Compliant World. Although, instead of using a class name, it uses the more semantic rel attribute.

4 . Jason Barnabe on January 24th, 2007

Jason Barnabe

The most correct answer is "don't open a new window". Opening new windows is bad for usability because it breaks the normal behaviour of web pages (for example, back buttons). If the user wants a link opened in a new window, the user knows how to do it themselves.

The second most correct answer is "don't use XHTML 1.1". Any benefits received from using XHTML are offset by the fact that the page won't work for 80% of users out there.

The third most correct answer is "use the target attribute anyway". I don't think any browsers out there will ignore the target attribute just because you claim to use XHTML 1.1 in the DOCTYPE. If you're already sending XHTML as text/html for IE users, what's wrong with another non-standard "compromise"?

I would say that using the script provided is fine as a fourth-best solution, but if you MUST open a new window, and you're standards-crazed enough that your site MUST be valid XHTML 1.1, why aren't you standards-crazed enough to reject the usage of non-standard ECMA script like window.onload, element.onclick, and window.open?

5 . Jesse Skinner on January 24th, 2007

Jesse Skinner

"why aren't you standards-crazed enough to reject the usage of non-standard ECMA script like window.onload, element.onclick, and window.open?"

I try to write code that people can easily copy and paste, and I want to keep the examples relatively simple. I always recommend people use addEvent instead of onclick, and addDOMLoadEvent instead of window.onload. Those who already know this will understand to use these, and those who don't won't be hurt by using old school JavaScript (until they wonder why their other window.onload function stopped working, I suppose).

That's why I give the jQuery example as well, so there's at least one "proper" example ;)

6 . Jason Barnabe on January 24th, 2007

Jason Barnabe

You chopped up my question. I wasn't asking "why are you using non-standard ECMA Script?". I was asking "Why are you using non-standard ECMA Script to avoid using non-standard HTML?" Even your jQuery example is non-standard with window.open, not to mention whatever jQuery itself does.

Reworded: given the choice between simply defining the non-standard target attribute in the HTML or writing a more complex, non-standard script which also has all the disadvantages scripting brings to the table, why would you choose the script?

7 . Jesse Skinner on January 24th, 2007

Jesse Skinner

I didn't mean to take your quote out of context, I just wanted to address why I use 'window.onload' in examples even though I'd never use it myself.

I agree with you that it's better to rely on a non-scripting solution, and that XHTML 1.1 isn't appropriate to use yet.. but maybe one day this blog post will be relevant.

8 . Jason Barnabe on January 25th, 2007

Jason Barnabe

"but maybe one day this blog post will be relevant."

Maybe, but maybe the target property of CSS 3 will gain support before XHTML 1.1 does.
http://www.w3.org/TR/css3-hyperlinks/#target0

9 . Jonathan Edmonds on January 27th, 2007

Jonathan Edmonds

Here goes, this is my first ever source code question so bare with me. I'm trying to embed my delicious links in a Joomla! wrapper. Delicious gave me this...

<script type="text/javascript" src="http://del.icio.us/feeds/js/jexzer?title=my%20del.icio.us;icon;name;showadd"></script>
<noscript><a href="http://del.icio.us/jexzer">my del.icio.us</a></noscript>

It works great but the links open in the same window which don't fit inside my Joomla! site. I want them to open in new windows. I tried your code in every way I could think of and couldn't get it to work. I very new at this and would appreciate some help. Thanks.

10 . Jesse Skinner on January 27th, 2007

Jesse Skinner

@Jonathan - the class name for delicious links is 'delicious-link', so you'd need to use that instead of 'new-window'.

If you already tried that, perhaps the problem is the script is being loaded too soon. Try adding it in a timeout to give some time for the delicious script to run, like so:

window.onload = function(){
setTimeout(function(){
// code above that changes the delicious links
}, 5000);
};

You could also try the approach of using setInterval to check the page every second until the links you want show up, then attaching the events and clearing the Interval.

11 . Jonathan Edmonds on January 27th, 2007

Jonathan Edmonds

You Rock. How did you know that 'delicious-link' was the class name?

Many thanks,
-JE

12 . Terry on February 1st, 2007

Terry

This code was created by someone else...not trying to bust your balls here or anything. At least give credit where credit is due:

http://www.456bereastreet.com/archive/200610/opening_new_windows_with_javascript_version_12/

13 . Jesse Skinner on February 1st, 2007

Jesse Skinner

@Terry - Obviously I didn't copy Roger's script, just wrote my own code to accomplish the same thing. Actually, I've never seen Roger's solution until now. But his is also nice (albeit much more complex).

14 . Terry on February 2nd, 2007

Terry

You are correct...and like I said, I wasn't trying to bust your balls on this. If you look at other versions and other people's customizations...they all derived from his code (just like all versions he published pre 1.2 or which ever version it's on.)

When I saw your code...and logic...the first thing that came to mind was his code. You may very well have written it all on your own, but it's similar enough that I wasn't the only one that noticed.

Side note: I do enjoy your site and use it when I find useful information. Keep it up!

15 . H5N1 on February 7th, 2007

H5N1

You inserted some text in "blockquote" TAG so this page is not valid XHTML:

Error Line 36 column 12: character data is not allowed here.

<blockquote>In XHTML 1.1 we cannot use attribute...

16 . Ray on February 7th, 2007

Ray

..."solution, and that XHTML 1.1 isn't appropriate to use yet.."

Can you guys please elaborate??

Thanks! :)

17 . Martin Kliehm on February 28th, 2007

Martin Kliehm

There are yet more ways to use the target attribute in XHTML 1.1, without script and totally standard conforming. After all, XHTML is extensible! http://learningtheworld.eu/2007/xhtml-with-target/

18 . ricardo prado on March 10th, 2007

ricardo prado

it wont be more simple:

<a href="http://www.blablabla.br"
onclick="this.target='_blank'">

19 . mike on March 14th, 2007

mike

Yes it will:
<a href="http://www.blablabla.br"
onclick="target='_blank';">

20 . VARA on July 10th, 2007

VARA

If the user viewing the page has javascript disabled, then the hole thing doesn't work.
So, I think, javascript is not the solution to the <target="blank"> validation problem with XHTML strict 1.1
In other words, let's hope that W3C gives a solution in the future...

21 . Michalis on August 31st, 2007

Michalis

Comment 19 works perfect.

22 . I Bap on September 25th, 2007

I Bap

onclick="this.target='_blank'"

This works with xhtml 1.1 and is valid for www.w3.org.

Thank You

23 . old timer on October 25th, 2007

old timer

Just another reason why I stick to nothing newer than HTML 4 with JS and CSS as needed.

24 . Adam on November 16th, 2007

Adam

After reading this post the code is slick for jquery.
Here is a mod:
//get the click to open popup
$(document).ready(function() {
$('a[rel*=link]').click(function(){ window.open(this.href);
return false;
});
});

Anyway this will open up a new window based on the 'rel' attribute. Web semantic as it should be.
For the rest of you whining about XHTML.
Get with the program.
If I was hiring you and looked at your code (especially old timer guy) I would not hire you.
Maybe go back to Frontpage.

Wicked post.
Jquery rules!

25 . fedmich on February 17th, 2008

fedmich

Nice code. Jquery rocks.

I was about to apply that trick to my portfolio page, http://www.fedmich.com/works/ but in the end I just simply changed doctype, its much easier that way

Cheers to all :)

26 . kiflea1 on June 2nd, 2008

kiflea1

I agree with Jason Barnabe. Don't use a new window.

The standards way of opening up a popup window is to use a floating div.

Jason
"Any benefits received from using XHTML are offset by the fact that the page won't work for 80% of users out there.
"
Jason, I disagree with you on that. Most browsers support xhtml.

27 . adam on June 3rd, 2008

adam

I find it funny that someone would say not to use a new window and use a floating div instead.
What happens if it is an offsite link?
Do you want your clients site users going to other sites and not returning?

Bringing standards into this is a poor excuse.

28 . Charles Bash on September 17th, 2008

Charles Bash

I think the base question that I see here is "why would anybody want to open "new windows" as it destroys the use of the "back button".

I was originally on the same page, but I have many links that go outside my site, and users complained "how did I end up on some strange site and not on your site" So I changed my code so that when on my site, I stay in the same browser window, but when going to other sites, I start a new window.

Users have to recognize that there are now two windows (or with tabbed browsers, potentially a new tab), so this is also potentially confusing. But it does allow somebody to maintain their context on my site while also viewing information from another site.

Since TARGET seems to be in XHTML 1.2, it would seem others agree that this is a valid user dynamic.

29 . adam on September 23rd, 2008

adam

Mr. Bash. It is all a matter of opinion and what the client wants.
One client wants a new window to open cause his demographic is old. The other wants people to use the backbutton.
If people are not using a tabbed browser where does it leave them?
I guess you build sites for people using Tab Browsers only?

"Since TARGET seems to be in XHTML 1.2, it would seem others agree that this is a valid user dynamic."

Seeming there is no final (or valid DTD-doctype) version for XHTML 1.2, why start building for it?

I guess XHTML 2.0 is in the draft phase too.
http://en.wikipedia.org/wiki/XHTML#DOCTYPEs

Looking at the articles that surround XHTML 2.0 people are not migrating cause of cross browser issues.

So where does it leave this debate..

No where. I have work to do and clients to keep happy.

30 . Noam on January 22nd, 2009

Noam

Why not :
$(document).ready(function(){
$('[rel=outer]').attr('target','_blank');
});

Why using window.new?

31 . Noam on January 22nd, 2009

Noam

*meant window.open

32 . Jesse Skinner on January 22nd, 2009

Jesse Skinner

@Noam - setting target=_blank will PROBABLY work, but really you're trying to use a feature of HTML with XHTML 1.1. It's kind of a hack since the browser doesn't have to implement the target="_blank" for XHTML 1.1 documents, you're just assuming they will.

If you want target=_blank you can always just use XHTML 1.0 or HTML of course. This is probably the best solution.

33 . Noam on January 22nd, 2009

Noam

:D
Didn't think about it with this perspective...
Good thinking!

34 . Santosh kori on February 9th, 2009

Santosh kori

Good trick,
It helped me in XHTML Validation.

Thanks
:)

35 . Prem ypi on March 4th, 2009

Prem ypi

This is neat code.

But the question persists, do we really need to use xhtml?

to me strict sounds good, whether html or xhtml should not matter though. Thats separate thing, that html strict also doesn't allow target parameter!

36 . Matthew Hartman on July 13rd, 2009

Matthew Hartman

Awesome trick, keep up the great work!

37 . Harshit on September 1st, 2009

Harshit

The solution you provided uses window.open. Window.open is stopped by all pop-up blockers which quite a few of the users have installed. Dynamically adding target=_blank is the way to go as the browser will not stop it and it will remain XHTML 1.0 Strict compliant.

I have a little code to share. This will automatically add a target=_blank to all external links whereas not do anything to internal links:

$(document).ready(function() {
$("a").filter(function() {
return this.hostname !== location.hostname;
}).attr('target', '_blank');
});

Cheers!

38 . Harshit on September 1st, 2009

Harshit

@Jesse's comment at 32

The reason target=_blank is depreceated is because of usability & accessibility concerns when opening a new window.. It is not because the words 'target=_blank' are evil.

By using window.open, you are effectively doing the same function as target=_blank. Only difference is that W3C XHTML does not apply to javascript so it does not catch it. So whether you use target=_blank or window.open, both of them are not good for usability purpose. But alas, clients are kings!

If

39 . skydrv on September 5th, 2009

skydrv

Thanks for your article Jess, just a question: is it right that the "onclick" function acts as a "nofollow" attribute? In other words, does google follow the links opened by javascripts? Thanks in advance! :)

40 . Jesse Skinner on September 7th, 2009

Jesse Skinner

@skydrv - I believe that's correct, Google doesn't seem to parse out any URLs used in JavaScript.

It's better to use robots.txt and rel="nofollow" instead if you can, though, so that your links don't require JavaScript and break for users that can't or don't want to use JavaScript.

41 . Aram on September 13rd, 2009

Aram

Viill lära mig HTML, har ni några tips på varifrån jag ska påbörja! TACK!

42 . Don Pedro on September 26th, 2009

Don Pedro

I justed converted various links
in files "XHTML1.0 transitional" (to make them fit to "strict", too),
to the format like message 19:

<a onclick="target='_blank';" href="http://domain.com/indxxxx.htm\">

Now I learn from message 39 + 40 that this would perhaps result in "nofollow" for Google.
This is no problem for links to others.

But this would be a problem in the typical case when we generate natural true content-inserted links between our own sites. Google would not count them in the backlink sum, while being full value links.

Messages 39 + 40 express "probably". Is here somebody who can confirm by sure the google crawler behavior related to this?

43 . Don Pedro on September 26th, 2009

Don Pedro

add-on to Comment 42:
My first opinion:

The Google problem probably concerns the case that Javascript has totally taken oven the link generation. The Google crawler does (probably) not include a simulator of the Java interpreter.

In the example in Comment 42,
<a onclick="target='_blank';" href="http://domain.com/indxxxx.htm\">
the link is still HTML code, not Javscript. I suppose that Google will take the link like any other usual link.

Possibly, Google will just do nothing with the included:
onclick="target='_blank';"

And I suppose that the Google quality evaluation of links will,
=== in general, ===
not make a difference in case of inclusion of a "open tab" functionality like:
target="_black"

We do not like the word "suppose".
Is there somebody who knows far more than me about this? :-)

44 . Ian on November 20th, 2009

Ian

It seems like even though that is technically valid according to the letter of the standard, you're still violating the spirit of the standard. So what's the point? Why jump through hoops when nothing is really different? If you're going to violate the standard, just use target="_blank" and own the decision.

45 . Abhi on December 22nd, 2009

Abhi

I want to do a jquery POST in a new window (popup). Basically trying to open up a print version of a page. So POSTing the data and then receiving the response in a new popup window is what I am trying to achieve. Any pointers will be helpful.

46 . Hi Abhi on December 22nd, 2009

Hi Abhi

There are enough posts on the internet which will guide you through this. As an example, checkout what i did for one of my client: http://www.direct-pharmacy.co.uk ... Add a product to the compare basket and on the left hand side block click on 'compare items'. It posts data to a new window. You can check its source to see its implementation..

As a hint, you need to start playing with form target="blah blah"

I have also implemented posting form data from pop window to parent window. Check out 'compare' feature on http://www.diamond-heaven.co.uk 's product page.. Click on 'Add to Basket' when the pop window opens..

Give me a shout on [email protected].co.uk if you have any questions...

47 . Mahesh on January 28th, 2010

Mahesh

Hey Brothers,

this is best script ....i spend hrs and after i got this page and thanks thanks thanks to Mike :-)

<a href="http://www.blablabla.br"
onclick="this.target='_blank'">

48 . anony on June 22nd, 2010

anony

@ Jason Barnabe,
Sorry I just read the boring rant by you, and felt compelled to comment! Just clicking you name shows me you have no style.

49 . tuba on July 5th, 2010

tuba

Nice info!

I am using <a href="http://www.blablabla.br" onclick="this.target='_blank'"> seems perfect!

50 . Lully on July 7th, 2010

Lully

Thank you for your code, your comments and the discussion here. I learnt a lot about about this topic.

51 . dpmguise on January 27th, 2011

dpmguise

Seeing as this conversation has already spanned 3 years, I felt the desire to keep it going.

Thanks to everyone's comments on this topic, I don't know if I am much clearer but I certainly understand the situation much better.

My thoughts are with others where, if you're trying to reach strict standards, then don't attempt to open a new window - that's what the people who made the standards are trying to emphasis... it should be a user decision...

If you're just trying to beat the W3C validator to appear that your page is standard... use one of the many suggestions provided... my preferred is onclick="this.target='_blank'" due to it's similarity with the original code...

Thanks to everyone, great read!

52 . Vic Dinovici on December 29th, 2011

Vic Dinovici

This works fine as well:

$(".external").attr("target","_blank");

or if you don't like creating classes for each external link:

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

in translation for each link starting with http:// ad target="_blank". This is assuming that the internal links have relative paths.

Comments are closed, but I'd still love to hear your thoughts.