Setting target=“_blank” to external links
If you want your pages to be valid XHTML-Strict, but you also wish to open external links in new window, the following snippet is doing just that—sets attribute target=“_blank” to all external links in a document to keep your code valid XHTML-Strict. You’ll just have to change variable yourURL. Don’t enter http://www. part of your domain, otherwise something like http://sample.com/ will be treated like any other external link.
// change your domain name:
var yourURL = "sample.com";
function outLinks() {
var outLink;
if (document.getElementsByTagName('a')) {
for (var i = 0; (outLink = document.getElementsByTagName('a')[i]); i++) {
if (outLink.href.indexOf(yourURL) == -1) {
outLink.setAttribute('target', '_blank');
}
}
}
}
window.onload = function() {
outLinks();
}

4 Comments
Nice snippet, but why open new windows? I mean, every user may open page in new window or tab if he wants. Moreover, your page with that script isn’t valid (X)HTML Strict, just W3 Validator thinks that it is.
Comment (#) by Vjekoslav — 29th November 2004.
Actually, what is so problematic as to set javascript: action for each link? Specially, when links are generated, this is easy. And from usability point of view, this opening links in new windows is bad habit.
BTW: why is this comment form so slow that it doesn’t catch up with me writing… it displays the letters with some delay. very ugly.
Comment (#) by dusoft — 29th November 2004.
I knew somebody will come on me for this : ).
You’re right, it’s not the right way to handle things, but if one has to, this is the most correct solution—separation of structure, presentation and behavior.
As for delay on comment preview script it’s probably due to slower CPU. The script listens more than just
onkeyupon the textarea, that’s why users with slower CPUs could experience slight slowdown.Comment (#) by marko — 29th November 2004.
Yeah OK, I know that separation is good. But it just kind of hack for now.
I have noticed that letters shows up at faster rate. Good.
Comment (#) by dusoft — 3rd December 2004.
Sorry, the comment form is closed at this time, but if you have anything to say, please send me a message.