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.


5 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

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.