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. User Avatar
    Paul Randall
    Permalink to comment#

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

    • User Avatar
      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.

    • User Avatar
      Lisa
      Permalink to comment#

      Thank you, Paul! This came in handy.

    • User Avatar
      Kalyan
      Permalink to comment#

      Very useful technique. Thanks you so much

    • User Avatar
      Syed Hussaini
      Permalink to comment#

      Here is something that I believe will add a great value. I just tried to ignore any links that belongs to the site and identify the external links straightforward.

      $(function() {
         $("a[href^='http']:not([href*='zaha.in'])").each(function() {
             $(this).click(function(event) {
                   event.preventDefault();
                   event.stopPropagation();
                   window.open(this.href, '_blank');
              }).addClass('externalLink');
         });
      });
      
  2. User Avatar
    Kris Millsap
    Permalink to comment#

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

  3. User Avatar
    Pico RG
    Permalink to comment#

    Nice solution

  4. User Avatar
    Mike Smith
    Permalink to comment#

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

  5. User Avatar
    nachomaans

    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. User Avatar
    Nicolas Gallagher

    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. User Avatar
    Scott Corgan

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

  8. User Avatar
    Federico Capoano

    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?

    • User Avatar
      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?

    • User Avatar
      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. User Avatar
    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. User Avatar
    Justus

    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. User Avatar
    ben

    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. User Avatar
    Praveen
    Permalink to comment#

    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. User Avatar
    satyam
    Permalink to comment#

    Hi…

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

    Thanks

  14. User Avatar
    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. User Avatar
    Bilal Niaz Awan
    Permalink to comment#

    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. User Avatar
    Shaun Robinson
    Permalink to comment#

    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. User Avatar
    Shaun Robinson
    Permalink to comment#

    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. User Avatar
    eL Abee
    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
    • User Avatar
      Kelly Johnosn
      Permalink to comment#

      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="https://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. User Avatar
    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. User Avatar
    Grover Campos
    Permalink to comment#

    Excelente tip, gracias

  21. User Avatar
    Kelly Johnosn
    Permalink to comment#

    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. User Avatar
    Mike
    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;
    		}
    	});
    });
    • User Avatar
      Mike
      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. User Avatar
    Konstantin
    Permalink to comment#

    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. User Avatar
    Adam

    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. User Avatar
    Jon Balza
    Permalink to comment#

    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. User Avatar
    ilanko
    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. User Avatar
    Rafael Cortes
    Permalink to comment#

    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. User Avatar
    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. User Avatar
    Roomi
    Permalink to comment#

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

  30. User Avatar
    Jacob Magnusson
    Permalink to comment#

    Probably the most efficient:

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

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

  32. User Avatar
    Sators
    Permalink to comment#

    Love it – thanks for the snippet!

  33. User Avatar
    Regan
    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. User Avatar
    jozsef kerekes
    Permalink to comment#

    I’m loving this solution, great ideea.

  35. User Avatar
    Karl Groves
    Permalink to comment#

    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. User Avatar
    Alan P.
    Permalink to comment#

    Thanks guys… y’all are awesome!

  37. User Avatar
    Eddy
    Permalink to comment#

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

  38. User Avatar
    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. User Avatar
    Jason Lengstorf
    Permalink to comment#

    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. User Avatar
    Debbie
    Permalink to comment#

    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. User Avatar
    Shin
    Permalink to comment#

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

  42. User Avatar
    Shin
    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.

  43. User Avatar
    Dave
    Permalink to comment#

    Yo all,
    I cant seem to figure out how to open this one up in a new window when dropped. Its a Drag and Drop function. It works, but it does not open up a new window.

    Can anyone help me out here?

    (function() {
                    var body = document.body,
                        dropArea = document.getElementById( 'drop-area' ),
                        droppableArr = [], dropAreaTimeout;
    
                    // initialize droppables
                    [].slice.call( document.querySelectorAll( '#drop-area .drop-area__item' )).forEach( function( el ) {
                        droppableArr.push( new Droppable( el, {
                            onDrop : function( instance, draggableEl ) {
                                // show checkmark inside the droppabe element
                                classie.add( instance.el, 'drop-feedback' );
                                clearTimeout( instance.checkmarkTimeout );
                                instance.checkmarkTimeout = setTimeout( function() { 
                                    classie.remove( instance.el, 'drop-feedback' );
                                    action = $(instance.el).data('action');
                                    href = $(draggableEl).data('href');
    
                                    switch(action) {
                                        case 'openUrl':
                                            window.location = href
                                            break;
                                        case 'tweet':
                                            // code block
                                            break;
                                    }   
                                }, 800 );
                                // ...
                            }
                        } ) );
                    } );
    
  44. User Avatar
    DaveE
    Permalink to comment#

    Hey all, I’m trying to do this on a SharePoint 2007 Webpart page, where I am using the Page Viewer Web Part to include a page of links we use a lot. Now, I want to put some code in a CEWP that will cause on-click of any of those links to open in a new page. Tried your code above but to no avail. Any thoughts?

  45. User Avatar
    idiv
    Permalink to comment#

    if the Iframe has external content, how read <a href link block by security error

  46. User Avatar
    Sohaib
    Permalink to comment#

    What if I want to open external site links (further pages) in same div where the site displays, without moving to next page or without changing URL. Just need to open in same div where external site already show.

  47. User Avatar
    Alfred
    Permalink to comment#

    If you have, as it was in our case, dynamically ajax-loaded links then you could add target=”_blank” on every link added after document is loaded.

    Or you could add this fine, well cooked, piece of code to your document ready-function.

    function openAllExternalLinksInANewWindow() {
        $(document).on('mousedown', 'a:not([href*="mailto:"],[href*="javascript"])', function (e) {
            var isInternalLink = new RegExp('/' + window.location.host + '/');
            if (!isInternalLink.test(this.href)) {
                $(this).attr('target', '_blank');
            }
        });
    }
    

    Whenever you “mousedown” anywhere in the site, and the target of the “mousedown” is an a-element with no mailto or javascript in the href attribute, check if it is link to an external page. If it is, set it’s attribute target to “_blank”. Scince it’s binded to the document and not the a-element itself, it doesn’t matter if the link is loaded after the document.ready-function.

    • User Avatar
      Sohaib
      Permalink to comment#

      Alfred, I have a situation.

      <div id="showresult"></div>
      <script>
            $("#showresult").load("http://css-tricks.com");
      </script>
      

      I get the result in my “showresult” div. What should I do if I want to show other pages inside the same div “showresult” when clicking on the links. I don’t want the links to open on new window or in same window, I want them to open in same div “showresult”.

  48. User Avatar
    rahul
    Permalink to comment#

    how to open chrome window using javascript program

    if webpage opened in firefox and want to open chrome by click the page that is open in firefox

  49. User Avatar
    Jeremy

    Thanks for this tip, Chris. The second jQuery snippet, with a mod to the specific URL needed, made it easy to open redirections of specific URLs in a new tab – on a WordPress site where I could add custom javascript but not easily change the Redirection plugin (nor any relevant options). So the jQuery appends the “_blank” to the URL before it reaches the plugin, and then the Redirection plugin does its job. Cheers!

  50. User Avatar
    Olivier C
    Permalink to comment#

    With Vanilla JS:

    function externalLinks() {
        var anchors = document.querySelectorAll( 'a' );
        for( var i = 0; i < anchors.length; i++ ) {
            if ( anchors[i].hostname !== window.location.hostname ) {
                anchors[i].setAttribute( 'target', '_blank' );
            }
        }
    }
    externalLinks();
    

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag