Using JQuery To Open External Links In A New Window

19th February 2010

Opening external links in a new window can be useful, but adding target="_blank" can be a real chore. Not only that, but if you are trying to validate the page to XHTML strict then the target attribute will cause errors to appear as it is not defined in XHTML.

An easy solution to this issue is to add the following JQuery to your site. It will look for any links that start with http and do not contain the current domain and add a new click event to them that causes a new window to be opened. This will exclude most links straight away as they will most likely be relative.

  1. $("a[href^='http']:not([href*='example.com'])").click(function(){
  2. window.open(this.href);
  3. return false;
  4. }).attr("title", "Opens in a new window");

This code will also add a new title to each link, replacing any that already exist, just remove the call to attr() at the end of the block to stop this. If you are using this on your site then make sure you put this into a dom ready block, and also that you change the example.com to be your own domain name.

Comments

Permalink
Thank you for taking the time to provide such a great snippet! I was wondering what would need to be added to this code to set the height and width of this new pop up window? Much appreciated!!

Anonymous (Mon, 10/11/2010 - 17:52)

Permalink

This is a pretty good resource:
Window open() Method

So, in adapting the above snippet you would get:

  1. $("a[href^='http']:not([href*='example.com'])").click(function(){
  2. window.open(this.href,'','width=200,height=100');
  3. return false;
  4. }).attr("title", "Opens in a new window");

philipnorton42 (Mon, 10/11/2010 - 20:38)

Permalink

I like to use the following:

  1. $("a[href*='http://']:not([href*='"+location.hostname.replace("www.","")+"'])").each(function() {
  2. //do some 'stuff' to the external link
  3. });

I also like to add an external class to the link for styling and also use:

  1. $(this).click(function(event) {
  2. window.open(this.href, '_blank');
  3. });

Full code and examples at:
jquery external links in new window

Unseen Revolution (Thu, 09/22/2011 - 22:21)

Permalink
  1. $(function(){
  2. $("a[href^='http']:not([href^='http://'+window.location.hostname.toLowerCase()])").attr({
  3. target: "_blank",
  4. title: $(this).attr('title')+" - this link will be open in a new window"
  5. }).append(' [^]');
  6. });

Alireza (Mon, 10/03/2011 - 05:38)

Permalink

thank u very muchhhhhhhh

it's help me

mojgan (Sat, 12/31/2011 - 08:04)

Permalink
is this method still operational in 2017?

ordenadores Madrid (Thu, 09/07/2017 - 10:13)

Add new comment

The content of this field is kept private and will not be shown publicly.