JavaScript

  1. Home
  2. Computing & Technology
  3. JavaScript

Targetting External Links to New Window

clr gif
Join the Discussion

Questions? Comments?

Some people like to set up the links on their web site so that those that go to other sites open in a new window. This is normally done by adding a target="_blank" attribute to those links.

If you don't want to have to go through all of the pages of your site to add those attributes where they are needed or if you want to be kinder to those with disabilities by only opening pages in a new window when Javascript is enabled then the following code is just what you are looking for.

function externalLinks() {
if (!document.getElementsByTagName) return;
var anchors = document.getElementsByTagName("a");
for (var i=anchors.length-1; i>=0; i--) {
var anchor = anchors[i];
if (anchor.href && anchor.href.substr(0,7) == "http://")
anchor.target = "_blank";
}
}
window.onload = externalLinks;

With that code added into the head of your web pages any fully qualified (absolute) links will automatically open in a new browser window while relative links will open in the same window with no target attributes being required in your HTML. The Javascript will automatically add the target attribute to any link where the href starts with http:// for you.

Explore JavaScript

About.com Special Features

JavaScript

  1. Home
  2. Computing & Technology
  3. JavaScript
  4. Controls and Widgets
  5. Functions
  6. Targetting External Links to New Window

©2009 About.com, a part of The New York Times Company.

All rights reserved.