< Back

Create HTML Links that Open in a New Window

2012-07-30

Introduction

When you create a link in HTML using the <a> tag, the link opens by default in the current window. Sometimes it is desirable to create links that open in a new window when clicked by the user. For example:

Basic Solution

The simplest way to create a single link that, when clicked, opens the link in a new window, is to add a target attribute to the link element. For example:

<a href="/" target="_blank">Link text</a>

The target="_blank" indicates that the link should be loaded into a new, blank, window.

A Cleaner Solution for Entire Sites

When maintaining large sites, a cleaner solution can be obtained by using JavaScript. This allows the link functionality to be changed simply without modifying every HTML document and also allows additional functionality to be added, such as tracking clicked links.

First, markup must be added to the HTML to indicate which links should be processed. I like to use the rel attribute and set its value to "external" for links to locations outside of the current site:

<a href="http://www.google.com/" rel="external">Outside Link</a>

There is nothing special about the term "external". This is simply an identifier that I chose to use.

Now we need some JavaScript that finds all the links that have their rel attributes set to "external" and process them as desired:

function externalLinks() {
	if (document.getElementsByTagName) {
		var anchors = document.getElementsByTagName("a");
		for (var i = 0; i < anchors.length; i = i + 1) {
			var a = anchors[i];
			if (a.getAttribute("href") &&
				a.getAttribute("rel") === "external") {
				a.target = "_blank";
			}
		}
	}
}

window.onload = externalLinks;

If you like to use the JQuery framework for JavaScript, the above code can be written as:

$(document).ready(function()
{
	$('a[rel="external"]').attr("target", "_blank");
});