WP-Mix

A fresh mix of code snippets and tutorials

jQuery Open Links in New Tab

Over the years, I’ve collected various JavaScript techniques for opening external links in their own tab. Here they are, all in one convenient post..

Pure JavaScript technique

This method opens all external links, as well as all nofollow external links, using plain JavaScript:

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

The only requirement for the links is that they must include the rel attribute with a value that includes external.

jQuery techniques

Here are some simpler open-external-links techniques that use jQuery:

jQuery(document).ready(function($){
	$('a[rel*=external]').click(function(e) {
		e.preventDefault();
		window.open(this.href);
	});
});

You can also do this:

$('a[rel="external"]').attr('target', '_blank');

..and this:

$('a[rel^="external"],a[rel$="external"]').attr({target:"_blank"});

The permutations are endless ;)

Targeting external links

If you want to target all links that point to a different domain, try this jQuery code snippet:

$('a[href^="http://"]').not('a[href*=wp-mix]').attr('target','_blank');

This code checks for the domain/keyword, and then adds a blank-target attribute to any non-matches. You can change the wp-mix to match your own domain. It’s a handy little snippet that can make targeting external links super easy. You could modify the code a bit to add a class for custom link styles or whatever floats your boat.

Resources

★ Pro Tip:

SES Pro