JQuery: Open external links in new window

Finally got round to writing a small bit of code to automatically force anchor links to open in new windows if they are for different domains:

$(document).ready(function() {
	var myDomain = ["www.ajgraham.com", "testing.ajgraham.com", "lifestream.ajgraham.com"]; //do NOT include the http:// pls!
	$("a[href^='http://']").each(function() {
		var slicedHref = $(this).attr('href').slice(7);
		var slashPosition = slicedHref.indexOf("/");
		if (slashPosition != -1) {
			slicedHref = slicedHref.slice(0,(slashPosition));
		}
		var matchCounter = 0;
		for (i=0;i<myDomain.length;i++) {
			if (slicedHref.indexOf(myDomain[i]) == -1) {
				matchCounter++;
			}
		}
		if (matchCounter == myDomain.length) {
			$(this).attr("target","_blank").attr("rel","external").append("<img class='new-window-link' alt='new window' src='http://www.ajgraham.com/wp-content/themes/ajgrahampro/images/external.png' style='padding-left:2px' />");
		}
	});
});

See Demo

Download basic example

Just remember to change

var myDomain = ["www.ajgraham.com", "testing.ajgraham.com", "lifestream.ajgraham.com"];

to your internal domain(s). You can use as many as you like, just don’t include the http:// bit.

blog comments powered by Disqus