Cody Marquart JavaScript, Groovy, and other technology tips

» jQuery links

Jul

15

Using jQuery to have external links open in a new window

By Cody

I usually find it best practice to have links to external sites open up in a new browser window or tab, however with some sites, you may not be in control of all the links entered. If you find yourself wanting to force all external links to perform this way, here is one line of jQuery to make all of your external links open in a window:

$("a:not([href*="+window.location.host+"])").attr("target","_blank");

It’s not foolproof, I suppose this would be a more robust version:

$("a:not([href^="+window.location.protocol+"//"+window.location.host+"])").attr("target","_blank");

Depending on your hostname, the first should be sufficient, but sometimes it better to play it safe.