batfan
5/1/2014 - 9:05 PM

Open all external links in a new window

Open all external links in a new window

$('a').each(function() {
	// The link's href
	var theHref = $(this).attr('href').toLowerCase();
	// The current domain
	var currentDomain = window.location.host;
	// Kill any subdomains
	var noSubDomain = currentDomain.match(/[^\.]*\.[^.]*$/)[0];
	// Create a new (case insensitive) regex from the clean domain
	var theDomain = new RegExp(noSubDomain, 'gi');

	if(/^https?/gi.test(theHref)) {
		// This link is using HTTP/HTTPs and is probably external
		if(theDomain.test(theHref)) {
			// Do nothing. For some reason, this site is using absolute internal links         
        } else {
			$(this).attr('target', '_blank');
		}
	}
});