06 Apr, 2011
launch all external links in a new window with jQuery
Posted by: Jennifer In: Javascript|jquery
This is a really simple piece of jquery that will launch all external links on the page in a new window.
jQuery(document).ready(function(){
jQuery("a[href*='http://']:not([href*='http://yourdomain.com'])").attr("target","_blank");
jQuery("a[href*='https://']:not([href*='https://yourdomain.com'])").attr("target","_blank");
});
Updated to add: Here is a modification in case you want to allow links to subdomains to open in the same window…
jQuery("a[href*='http://']:not([href*='http://yourdomain.com'])").not("[href^='http://subdomain.yourdomain.com']").attr("target","_blank");
Another update Here is another modification that will work in a PHP page and automatically enter the current domain in:
jQuery(document).ready(function(){
jQuery("a[href*='http://']:not([href*='http://<?php echo $_SERVER['HTTP_HOST']; ?>'])").attr("target","_blank");
jQuery("a[href*='https://']:not([href*='https://<?php echo $_SERVER['HTTP_HOST']; ?>'])").attr("target","_blank");
});