scriptygoddess

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");
});

1 Response to "launch all external links in a new window with jQuery"

1 | The Frosty

April 7th, 2011 at 9:58 am

Avatar

I like to do the same with a jQuery filter:

jQuery('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
}).attr('target','_blank');

Featured Sponsors

Genesis Framework for WordPress

Advertise Here


  • Scott: Just moved changed the site URL as WP's installed in a subfolder. Cookie clearance worked for me. Thanks!
  • Stephen Lareau: Hi great blog thanks. Just thought I would add that it helps to put target = like this:1-800-555-1212 and
  • Cord Blomquist: Jennifer, you may want to check out tp2wp.com, a new service my company just launched that converts TypePad and Movable Type export files into WordPre

About


Advertisements