Use jQuery to make external links open in a new window

June 11, 2008

I was just reading the comments of Raymond Camden's post about the best way to trim text and saw that someone was asking how to add target="_blank" to all external links. Now this can be done in ColdFusion using the CFMatch tag (a great addition to CF8!), but I'd let jQuery do the hard work for me. I posted my solution on Raymond's blog but thought I'd put it here as well.

Here's how...


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

Or if you want to get fancy:


$('a[href^="http://"]')
.attr({
target: "_blank",
title: "Opens in a new window"
});

You can even add an image or text to your hyperlink with a little bit of chaining. This example adds [^] to the end of your link text.


$('a[href^="http://"]')
.attr({
target: "_blank",
title: "Opens in a new window"
})
.append(' [^]');

Pretty neat huh! I should point out that these examples assume that all your external links start with http:// but the selectors in jQuery are powerful so you can filter by domain names etc.


24 comments

  1. Thx for posting this. :)

    Rey
    jQuery Team

    Comment by Rey Bango – June 12, 2008
  2. Great tip, except now I have to figure out how to disable the title and append if the link is an image. :-/

    Comment by GasGiant – June 12, 2008
  3. @GasGiant,
    Not quite sure what you're trying to do if you're only want to get links with an image to open in a new window then this will do it:

    $('a[@href^=""] img')
    .parent()
    .attr({
    target: "_blank"
    });

    Comment by John Whish – June 13, 2008
  4. Thank you very much for this. One quick question, how can I target all the links within a specific div only?

    Thanks,
    Josh

    Comment by Josh Ellington – June 23, 2008
  5. Hi Josh,
    If all your links are inside a div with an id of "mydivname" then this will do the trick:

    $('#mydivname a[@href^=""]') /> .attr("target", "_blank");

    Hope that helps.

    Comment by
    John Whish – June 24, 2008
  6. Nice lightweight and useful bit of code, gonna add it to my site later!
    Thanks
    Tom

    Comment by Tom James – December 10, 2008
  7. Very nice.
    I prefer this to using something like
    window.open(this.href);

    Comment by Andrew Henze – February 08, 2009
  8. Hi Andrew, yeah - I like it :)

    window.open does still have it's place as you can control the browser window chrome, position and size. It just depends on what you want to achieve. Of course you could combine the two and have something like this (no tested!)...

    $('a[href^=""]').click(function(){ /> window.open( this.attr('href'), "foo", "width=100,height=100" );
    return false;
    });

    Comment by
    John Whish – February 08, 2009
  9. Hi,

    This doesn't work with jQuery 1.3.1 - only 1.2.6. Any suggestions on how to fix that, please?

    David.

    Comment by David – February 10, 2009
  10. Hi David, the code in the post works for me in 1.3.1. What are you trying to do?

    Comment by John Whish – February 10, 2009
  11. Hi John,

    Thanks for the reply.

    I found out the cause of my problems a couple hours ago. I run most of my HTML through HTML Tidy (via www.topstyle4.com/) to check for errors and format it. Part of that forces CDATA around embedded JavaScript to make it validate as XHTML. For some reason that was FUBARing it.

    Solution: strip CDATA or move code to external file.

    Thanks for sharing the code.

    Cheers,

    D.

    Comment by David – February 10, 2009
  12. The "Non-tested" version with the window params does not work. I get a runtime error.

    CODE:

    $('a.video[@href^=""]').click(function() {
    window.open(this.attr('href'), "NewWin", "width=800,height=600");
    return false;
    });

    Comment by John – November 02, 2009
  13. @John, the use of the '@' sign is deprecated. Try:

    $('a.video[href^=""]').click(function() {
    ...code...
    });

    Comment by John Whish – November 03, 2009
  14. Hum .. i'm using the full url in nearly all of my projects, so my version looks like this:

    [code]
    $('a[rel*="external"]').live('click',function(){ this.target='_blank'; });
    [/code]

    window.open() is ok, but recognised as "low quality" or "spammy" stuff by so many tools...

    i guess the best option is to check window.location.host against every single link. but i didn't try it - user-experience etc.

    Comment by jQuery Agentur – November 17, 2009
  15. Hi,

    Great tutorial!

    I was wondering how can you mkae it open up under the current window? So if a user clicks it, it opens as a pop-under (For lack of a better term)

    Cheers

    Comment by Ben – December 29, 2009
  16. I'm trying to open a new window in jqGrid 3.5 in the onCellSelect: function(rowid,iCol,cellcontent) event following the code I found here. With the below code I get nothing, no errors, no response in both FF and IE 7. Any ideal on what I'm doing wrong? Thanks, Jim

    $('a[href="myserver/pti/parview/#shipdetail.cfm?ThisSN="+cellcontent]') .attr("target", "_blank");

    Comment by Jim Papaleo – May 11, 2010
  17. @Jim, I think you might have a problem with you quotes. Assuming that cellcontent is a variable, then you want to do this:
    $('a[href="myserver/pti/parview/#shipdetail.cfm?ThisSN='+cellcontent+'"]').attr("target", "_blank");

    Comment by John Whish – May 11, 2010
  18. John, thanks for the quick reply, but it didn't solve the problem. The cellcontent is returned from the onCellSelect function.

             onCellSelect: function(rowid,iCol,cellcontent){
    if (iCol == 0)
    $('a[href="myserver/pti/parview/#shipdetail.cfm?ThisSN='+cellcontent+'"]').attr("target", "_blank");
    },
    ------
    If I use this line instead of the above it works:
    {window.location.href = "shipdetail.cfm?ThisSN="+cellcontent;}
    -----
    but it opens in the same window and I want it to open in a new window.

    Comment by Jim – May 11, 2010
  19. @jim, why don't you use:
    window.open("shipdetail.cfm?ThisSN="+cellcontent, "windowname")

    Comment by John Whish – May 12, 2010
  20. Thanks John,

    That worked.

    Comment by Jim – May 12, 2010
  21. Hi, this is great, most succinct version I've seen.

    I'm trying to add to it, and totally stuck. What I want additionally is to have the url of the link added to the title attribute, eg.

    "www.somesite.com/some-page/ - external link, click to open in a new window"

    Can you help?

    Comment by aljuk – June 23, 2010
  22. @aljuk, you'd need to loop through the links to get it to do that. This should work:

    $('a[href^=""]') /> .each(function(){
    $(this).attr({
    target: "_blank",
    title: this.href + " - external link, click to open in a new window"
    });
    });

    Comment by
    John Whish – June 23, 2010
  23. Awesome, many thanks. I took it a little further, to catch any internal absolute links, this is working well :

    $('a[href^=""]').each(function(){ />if (this.hostname !== location.hostname) {
    $(this).attr({
    target: "_blank",
    title: this.href + " (external link, click to open in a new window)"
    });
    }
    });

    Comment by aljuk – June 28, 2010
  24. Hello,
    I stumbled upon this while trying to find the solution for a question. Im a blogger, and have only a very basic knowledge of technical aspects.

    In my blog (at
    www.mindlessmumbai.com/ ) I usually add the "_blank" to any links in my posts that I want to open in a new window.

    But, is there a way by which I can customise any of the scripts in this post, so that the comments page of every post opens in a new window? I can see that Blogger names the URL of the comments page as blogname.blogspot.com/YYYY/MM/postname.html#comments />
    Is there a way to use the " #comments " part of the URLs as a parameter in a script, to specify the links that open in a new window?

    Any help would be appreciated.

    Regards,
    Kunal

    Comment by
    Kunal Bhatia – July 25, 2010

Leave a comment

If you found this post useful, interesting or just plain wrong, let me know - I like feedback :)

Please note: If you haven't commented before, then your comments will be moderated before they are displayed.