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.
- Posted in:
- jQuery
- ColdFusion
5 comments
Leave a comment
If you found this post useful, interesting or just plain wrong, let me know - I like feedback :)

Rey
jQuery Team
Comment by Rey Bango – June 12, 2008
Comment by GasGiant – June 12, 2008
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
Thanks,
Josh
Comment by Josh Ellington – June 23, 2008
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