YUI2: Open links in new window

Simple YUI2 function to add the target attribute to external links in a specific container on the page after Dom ready.

I have written a basic javascript function to add target="_blank" to external links after page load so that they open in a new window.

First I create the function to add target="_blank" to an anchor tag, setting up a variable for the site URL and also one to define the site root as '/'.

I pass into the function a 'links' object which contains all the details of the links I want to check against. I loop thorugh all of the links removing any query strings then check to see if the URL matches either of my config preferences and if so I add target="_blank" to the tag:

function newWindow(links) {
	var siteRoot = '/';
		siteURL = window.location.hostname;
		i,
		linksHref;
	for (i = 0; i < links.length; i = i + 1) {
		linksHref = Dom.getAttribute(links[i], 'href');
		// Strip any query string off before checking the domain
		linksHref = linksHref.split("?")[0];
		if ((linksHref.match(siteURL) === null) && (linksHref.substring(0, 1) !== siteRoot)) {
			Dom.setAttribute(links[i], 'target', '_blank');
		}
	}
}

I specify the HTML element I want to check the links in and once it is ready on the page I then pass all those links to the 'newWindow' function:

Event.onContentReady('element-to-check', function () {
	links = this.getElementsByTagName('a');
	newWindow(links);
}, this);

Requires the following YUI2 files:

/*global window, document, YAHOO */

YAHOO.namespace('yourNamespaceHere');
YAHOO.yourNamespaceHere = (function () {
	'use strict';
	var init,
		Dom = YAHOO.util.Dom,
		Event = YAHOO.util.Event;

	function newWindow(links) {
		var siteRoot = '/';
			siteURL = window.location.hostname;
			i,
			linksHref;
		for (i = 0; i < links.length; i = i + 1) {
			linksHref = Dom.getAttribute(links[i], 'href');
			// Strip any query string off before checking the domain
			linksHref = linksHref.split("?")[0];
			if ((linksHref.match(siteURL) === null) && (linksHref.substring(0, 1) !== siteRoot)) {
				Dom.setAttribute(links[i], 'target', '_blank');
			}
		}
	}

	init = function () {
		// GET LINKS
		Event.onContentReady('element-to-check', function () {
			var links = this.getElementsByTagName('a');
			newWindow(links);
		}, this);
	};

	return {
		init: init
	};

}());
YAHOO.util.Event.onDOMReady(YAHOO.yourNamespaceHere.init);