/ Published in: JavaScript
Automatically use jQuery to Open External Links in New Window (checking domain first).
Expand |
Embed | Plain Text
// open external links in new window (checking domain first) jQuery("a[href^='http']:not([href*='" + document.domain + "'])").each(function () { jQuery(this).attr("target", "_blank"); });
Comments
Subscribe to comments
You need to login to post a comment.

I like to use the following for external links:
$(function() { $('a:not([href=""])').each(function() { if (this.hostname !== location.hostname) { $(this).addClass('externalLink').attr('target', "_blank"); } }); });It gives me the ability to insure that the links are actually external and also allows me to add a class the the external links for styling. For example adding an external link icon.
Full code can be found at:
jQuery External Links