Grow your CSS skills. Land your dream job.

Last updated on:

Open External Links In New Window

$('a').each(function() {
   var a = new RegExp('/' + window.location.host + '/');
   if(!a.test(this.href)) {
       $(this).click(function(event) {
           event.preventDefault();
           event.stopPropagation();
           window.open(this.href, '_blank');
       });
   }
});

You can do this straight with HTML, but that is invalid markup, this takes care of business without invalid code and unnecessary markup.

Or, you can still avoid the validation problems and just append the class target=_blank thing to any links with href attributes starting with http://. The example below only targets links in a #content area. Scoping down like that might be a good idea in case your menus are dynamic and create full URLs.

$("#content a[href^='http://']").attr("target","_blank");

Also note that there are a wide variety of different ways to only target external links.

Comments

  1. A slightly different version if you only want to target specific URLs (I use the rel tag “external”):


    $('A[rel="external"]')
    .click( function() {
    window.open( $(this).attr('href') );
    return false;
    });

    • Adam Clark
      Permalink to comment#

      Nice snippet Paul, that’s much better, and beautifully unobtrusive and validates in XHTML 1 strict. It’s about time the world stops using obtrusive javascript.

    • Permalink to comment#

      Thank you, Paul! This came in handy.

    • Kalyan
      Permalink to comment#

      Very useful technique. Thanks you so much

  2. Permalink to comment#

    Is there a way to resize the window that pops up as well?

  3. Permalink to comment#

    Nice solution

  4. This is awesome. Just what I needed for a client’s website. And thanks Paul, that works wonderful.

  5. Here is a snippet we’re using that works similar to Paul’s and adds support for target “_blank”, “parent”, “top” and “popup”

    function externallinks() {
    	if (!document.getElementsByTagName) return;
    	var anchors = document.getElementsByTagName("a");
    	for (var i=0; i<anchors.length; i++) {
    		var anchor = anchors[i];
    		anchor.tabindex = i;
    		if (anchor.getAttribute("href")) {
    			if (anchor.getAttribute("rel") == "external")
    				anchor.target = "_blank";
    			else if (anchor.getAttribute("rel") == "parent")
    				anchor.target = "_parent";
    			else if (anchor.getAttribute("rel") == "top")
    				anchor.target = "_top";
    			else if (anchor.getAttribute("rel") == "popup")
                    $('a[rel="popup"]').click(function(){return $.dbPopWin( $(this).attr('href'));}
    				);	
    		}
    	}
    }

    If code is garbled, grab it here: http://www.id3.co.th/js/lib.js (look for “links and popups”)

    You then activate it in your pages by adding externallinks(); in your $(document).ready(function(){

    If code is garbled, check the source of http://www.id3.co.th/ (look for “.ready(function”)

    Hope this helps!

  6. If you have a good reason for opening certain links in a new window and want to use plain HTML you could just switch to the HTML5 doctype.

  7. It’s the little things in life! Small code, huge solution!

  8. target=”_blank” and just forget about xhtml strict, that is dead by the way.
    Everyone is talking about HTML5 now.. why do you waste your time with thes insignificant problems?

    • Spartaco

      I agree with you, why bothering with scripts when we already have target”_blank”, moreover it also works for people with js is disabled! Maybe this isnt a concern anymore?

    • Colin
      Permalink to comment#

      Because, even in 2010, people still don’t understand the role of validation. It’s a tool, not an achievement. Remember the compliance badge craze!?

  9. csulok

    if you’re using jquery, you should use delagate. that way, you create 1 event binding on the body element, instead of hundreds, one on each link.

    code would look something like
    $(‘body’).delegate(“a”,”click”,function() {
    var a = new RegExp(‘/’ + window.location.host + ‘/’);
    if(!a.test(this.href)) {
    event.preventDefault();
    event.stopPropagation();
    window.open(this.href, ‘_blank’);
    }
    });

  10. Technically it’s a nice solution.

    On the other hand it might tempt designers to use it whenever they can. NEVER open up a new window unless it is absolutely necessary or is a 100% user-friendly. Having all external links open up in a new window is neither.

  11. For MooTools it’s very similar:

    window.addEvent('domready',function() {
    	var links = $(document.body).getElements('a[href^=http:]'); //link start with http != mailto
    	links.each(function(el){
    	el.addEvent('click', function(e){
    		e.stop();
    		(this.href.test('/'+window.location.host+'/')) ? window.open(this.href):window.open(this.href, '_blank');
    		});
    	});
    }); // domready
  12. Good one. I think, this post describes good about it and a perfect solution too!!!

    http://praveenbattula.blogspot.com/2010/06/open-all-anchor-links-in-new-window.html

  13. satyam
    Permalink to comment#

    Hi…

    Can i have any code to popup an iframe content dynamically……..

    Thanks

  14. helpin
    Permalink to comment#

    @nachomaans
    How can I have copied the code you given to section .But I am not sure If I follow this line:You then activate it in your pages by adding externallinks(); in your $(document).ready(function(){

    Where can I use it?

  15. I think my comment comes quite late with respect to this post but I have written a small jQuery plugin for the same based on knowledge gain my this post and my readings about jQuery plugin development in the last week or so. Please find the link to the plugin and associated post hope its upto the jQuery plugin development standards.

    http://www.uipress.com/extlink-a-jquery-plugin-to-add-target_blank-to-external-and-file-links/

    Regards,
    Bilal Awan

  16. A small optimization: since the RegExp doesn’t change , move it outside the loop so it is only defined (and compiled) once. No sense in redefining it on each loop occurrence.

    
     var a = new RegExp('/' + window.location.host + '/');
    ('a').each(function() {
       if(!a.test(this.href)) {
           $(this).click(function(event) {
               event.preventDefault();
               event.stopPropagation();
               window.open(this.href, '_blank');
           });
       }
    });
    

    Also, it’s worth noting that this only works if all internal links have a full absolute path. Since it compares it to the host name, each link must contain the host name. Relative links in the form /link/to/something or link/to/something will be treated as external links.

  17. I forgot the dollar sign in my code snippet! Here is the correct code:

    
    var a = new RegExp('/' + window.location.host + '/');
    $('a').each(function() {
       if(!a.test(this.href)) {
           $(this).click(function(event) {
               event.preventDefault();
               event.stopPropagation();
               window.open(this.href, '_blank');
           });
       }
    });
    

  18. Permalink to comment#

    How to use this code?

    I’m know nothing about jQuery, i just paste that code in HTML head, and i get this error in Chrome web inspector:

    Uncaught TypeError: Property '$' of object [object DOMWindow] is not a function
    • el Abee.. you have to first include the actual jQuery library and then, make sure the actual code you paste in is within <script></script> tags and that those two tags are within the <head></head> tags. And by the way, including jQuery needs to be done between the head tags too:

      <head>
      <script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
      
      <script type="text/javascript">the stuff you pasted goes here</script>
      </head>
      
  19. Sajid
    Permalink to comment#

    sir i have a problem that there are thumbnails in my page when a user clicks it i want to open the larger image of that thumbnail in a div new window tab

  20. Grover Campos
    Permalink to comment#

    Excelente tip, gracias

  21. Here is what we do:
    <a href=”somewhere” class=”newWindow”>

    and in the jQuery file we use:

    function setupNewWindow(){
    $(‘.newWindow’).click(function(){window.open($(this).attr(‘href’)); return false;});
    }

  22. Permalink to comment#

    I tried every variation I possibly could of using $(‘a[rel="external"]) I could think of. I used double quotes, single quotes, tried using [rel^="external"] in an attempt to just make the thing look for a link that begins with, I copied and pasted the code instead of typing it out. I made sure that arbitrary jQuery code would work in this scripts place. I made sure that my WordPress enqueue_script was working properly. I tried similar scripts from other websites. I’ve Googled til my fingers bled…

    …and still nothing that involves using [rel=""] works for me. I’m using the latest jQuery library from the jQuery CDN (1.7.1 minified @ the time I’m writing this comment). Am I missing something? Does this version of jQuery not pick up on [rel=""]?

    If I take the [rel="external"] out, it works, but for every link (which is to be expected since there’s no conditional). I wrote something else that works that’s a derivative, but the [rel="external"] just seems so much more elegant and I’d rather use that.

    Here’s my script:

    
    $(document).ready(function() {
    	var a = new RegExp( '/' + window.location.host + '/' );
    	$('a').click(function() {
    		if ( !a.test(this.href)) {
    			window.open($(this).attr('href'));
    			return false;
    		}
    	});
    });
    • Permalink to comment#

      Just noticed one thing about the first line in my comment above. $(‘a[rel="external"]) should be $(‘a[rel="external"]‘).

      Any ideas on why this is happening? :-(

  23. Sorry, I could be wrong, but the examples shown here do not work if the attribute with the “external” there is some attribute, such as, “nofollow” or “author”. I used to blog a little bit different code, taken from the plugin:

    jQuery(function(){jQuery('a[rel*=external]').click(function(){window.open(this.href);return false;});});
  24. Tried them all and couldn’t get them to work either…. that is till I tried the code from Konstantin, worked perfect and loaded super fast! Thank you thank you thank you…. saved much time and effort. Question: is it valid? Was usuing simple javascript before but was slow and clunky….(below).

    
    function externalLinks() { 
     if (!document.getElementsByTagName) return; 
     var anchors = document.getElementsByTagName("a"); 
     for (var i=0; i<anchors.length; i++) { 
       var anchor = anchors[i]; 
       if (anchor.getAttribute("href") && 
           anchor.getAttribute("rel") == "external") 
         anchor.target = "_blank"; 
     } 
    } 
    window.onload = externalLinks;
    
    

    Thanks again Konstantin!!!

  25. This works great, but the code does interfere with some Google Analytics features. For instance, we lost all of our outbound link tracking when using this.

  26. Permalink to comment#

    I have a site with multiple domain, none of the above have a solution for any domain, with or without www.

  27. I have to say that I like your code but I wanted the same effect but with less.
    So this is what I used on a project that I am updating.

    $(function() {
    $(“.targetBlank”).click(function() {
    window.open(this.href);
    return false;
    });
    });

    You could use this:

    $(document).ready(function() {
    $(‘.targetBlank’).click(function() {
    $(this).target = “_blank”;
    window.open(this.href);
    return false;
    });
    });

    Yet I chose the first one after testing it out. All you have to do here is add a [class="targetBlank"] to your links.

    I just want to join in the fun with you guys. Great post btw. :D

  28. Headmax
    Permalink to comment#

    I just include the script to take the target value (_top,_parent,_self,_blank…) directly.

    $(‘a’).each(function() {
    var a = new RegExp(‘/’ + window.location.host + ‘/’);
    var targets = this.target;
    if(!a.test(this.href)) {
    $(this).click(function(event) {
    window.open(this.href, targets);
    return false;
    });
    }
    });

  29. Very nice but you should update this post now with latest jQuery code to make all external links rel=”nofollow”.

  30. Jacob Magnusson
    Permalink to comment#

    Probably the most efficient:

    $('body').on('click', 'a[rel="external"]', function() {
        window.open($(this).attr('href'));
        return false;
    });
    
  31. yuvaraj
    Permalink to comment#

    $(this).attr(“target”, “_blank”); u can use this.it works fine…any queries msg me…yuvarajamsc12@gmail.com

  32. Permalink to comment#

    Love it – thanks for the snippet!

  33. Permalink to comment#

    Great. But, I want to open external links in new window except some links. Those links should be opened in _self target. Please help me.

  34. jozsef kerekes
    Permalink to comment#

    I’m loving this solution, great ideea.

  35. You can do this straight with HTML, but that is invalid markup, this takes care of business without invalid code and unnecessary markup.

    This is a pretty silly statement, as the code in the example adds the “invalid markup”. Whether or not it is in the document source or not, when rendered in the browser it is part of the document either way.

  36. Alan P.
    Permalink to comment#

    Thanks guys… y’all are awesome!

  37. Eddy
    Permalink to comment#

    Thank you so much, this saves me so much time. And learn a few thing myself!

  38. Maciek Baron
    Permalink to comment#

    This can actually be simplified to this:

    $("a").each(function () {
        if (this.hostname != document.location.hostname) this.target = "_blank";
    });
    

    HTMLAnchorElement also has the hostname property (which is preferred from host due to some cross-browser issues – IE8 for example will append the port 80 to the hostname even if it is not specified in the href).

  39. An option to target all external links without requiring classes or rel attributes:

    // Opens all offsite links in a new tab
    $("a[href^='http']").each(function(){
        if (this.href.indexOf(window.location.host)===-1) {
            $(this).attr("target", "_blank");
        }
    });
    

    NOTE: This hasn’t been tested in IE, because quite frankly this is kind of a bad idea in the first place and I don’t care if the links work like links are supposed to work in older browsers.

  40. This post was a great help, thank you. I can now easily add blog badges to my site and know that they are opening in a new window.

    If I can alter badge coding to make it open in a new link then anyone can!

  41. Permalink to comment#

    I have tryid Mike’s code, but it doesn’t work, anyone else?

  42. Permalink to comment#

    Hi, Jacob Magnusson, your code works fine, but it is only working on rel=”external”, but it doesn’t work on something like rel=”external nofollow”, is that any solutions? sorry I’m bad in javascript, just need help. Thank you.

Leave a Comment

Posting Code

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".