Open all external links in a new window

Sometimes you can’t control generated HTML containing external links, you’re desperately trying to keep your ancient XHTML document valid, or you don’t trust your CMS users to consequently set the target for external links. We can easily set all external links (starting with “http” and excluding our own domain) to open in a new window with jQuery:

function externalLinks() {
	$("a[href^='http']:not([href*='" + window.location.host + "'])").each(function() {               
		$(this).attr("target", "_blank");
	});
}

Call the function on document ready.

	$(document).ready( function(){
		externalLinks();
	});

If you also want to handle dynamically loaded content (with AJAX for example), you can use jQuery’s on event to attach a click handler, also to future links.

function externalLinks() {
	$( document ).on( "click", "a[href^='http']:not([href*='" + window.location.host + "'])", function() {         
		$(this).attr("target", "_blank");
	});
}

Leave a Reply