PSD to HTML conversion PSD to HTML conversion PSD2HTML.com with over 300 professionals takes the designs to HTML and beyond

Code Snippet

Home » Code Snippets » jQuery » Open External Links In New Window

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.

Subscribe to The Thread

  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 says:

      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.

    • Lisa says:

      Thank you, Paul! This came in handy.

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

  3. Mike Smith says:

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

  4. nachomaans says:

    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!

  5. 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.

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

  7. 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 says:

      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 says:

      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!?

  8. csulok says:

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

  9. Justus says:

    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.

  10. ben says:

    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
  11. Praveen says:

    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

  12. satyam says:

    Hi…

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

    Thanks

  13. helpin says:

    @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?

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~