If you are reading this, please get modern browser.
skip to main content | skip to main navigation | skip to secondary content

Setting target=“_blank” to external links

~ 29th November 2004. · 13:48 CET · permanent link · printer friendly ~

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

  1. 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.

  2. 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.

  3. 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 onkeyup on the textarea, that’s why users with slower CPUs could experience slight slowdown.

  4. 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.

Sorry, the comment form is closed at this time, but if you have anything to say, please send me a message.

* Please keep in mind that this is a personal web site and it does not reflect the position or opinion of my respective employers, organizations or partners.

Typetester – compare screen type Supported by Veer.

What is this?

A web log of Marko Dugonjić, web professional from Croatia. Topics covered:

Translate this site

German, Spanish, Italian, French or Japanese (via).

See you there!

Feel like buying a book?

Try with maratz.com aStore

Worth visiting

top of the page | skip to main content | skip to main navigation | skip to secondary content