Article
New-Window Links in a Standards-Compliant World
Deconstructing the Script
The job of our script, which will be run once the document is loaded, will be to find all the hyperlinks in the document and modify those that have our special (but standards-compliant!) rel="external" attribute, so that they open in a new window.
Sound daunting? Don't worry -- the code's not too bad. The first step is to make sure the browser is up to the task:
if (!document.getElementsByTagName) return;
getElementsByTagName is a handy method of the Document Object Model 1.0 (DOM1) standard supported by modern browsers. Since a few of the older browsers that are still hanging around, such as Netscape 4 and Internet Explorer 4, don't support DOM1, we need to weed them out by checking for the presence of this function. On those browsers, we simply return and let external links open in the same browser window -- no great loss, in most cases.
Next, we use the getElementsByTagName method to get a list of all the <a> tags in the document:
var anchors = document.getElementsByTagName("a");
anchors will contain a JavaScript array after the method does its job. Each element in the array will represent an <a> tag in the document.
Now we need to go through all of the <a> tags we just found and modify those that represent new-window links. You can use a JavaScript for loop to work on each of the tags in turn:
for (var i=0; i < anchors.length; i++) {
var anchor = anchors[i];
For each element in the anchors array, we create a variable inside the loop called anchor to isolate the tag with which we are currently concerned.
Now we need to check if anchor represents a new-window link. As I'm sure you know, the <a> tag isn't just used to create hyperlinks. With a name attribute, you can create a target for links that go to a particular location in the page. Only <a> tags with an href attribute qualify as hyperlinks. Our code must therefore check that anchor has an href attribute as well as a rel attribute that is set to external.
if (anchor.getAttribute("href") &&
anchor.getAttribute("rel") == "external")
Now that we've confirmed that we're dealing with a new-window link, we can set its target attribute to "_blank":
anchor.target = "_blank";
And that should do it! Read on for the complete code, and for a few more words on why this solution is acceptable...