(Updated 2/12/2010 and 2/24/2010:)
I like the jQuery solution in Justin Scheetz's comment on this article in badlyDrawnToy:
$(function() {
$("a[href*='http://']:not([href*='"+location.hostname+"'])").click(
function() {
window.open(this.href);
return false;
});
});
(Updated again 2/24/2010:)
Here's the jQuery for just setting the target attribute (with a little help from NerdyDork):
$(function() {
$("a[href*='http://']:not([href*='"+location.hostname+"'])").attr("target", "_blank");
});
(Updated again 10/06/2011:)
Found earlier that the above solution failed for https, so I had to add another line for that. And then found that the comparison for .hostname needs to be case-insensitive. So my latest solution is the following, using some tips from the electric toolbox (which also mentions that, with HTML5, "the W3C has un-deprecated the target attribute"):
$(function() {
$("a").filter(function() {
// find all links that have a hostname
// that doesn't match the current location
return this.hostname &&
this.hostname.toLowerCase() !== location.hostname.toLowerCase();
}).click(function() {
// open those external links on another window
window.open(this.href);
return false;
});
})
So the new way is to flag the relevant tags and then use JavaScript to iterate through all the tags on a page to see if any of them have the tag? Good grief, whose decision was it to make the code more verbose and add a bunch of unnecessary cycles by checking all the tags? :|
ReplyDeleteNo kidding. And did you see the date on that article? 2003! Maybe there's a better way to do it now. I'll need to check.
ReplyDeleteHaha, I'm so 2003. Yeah I think I'd prefer to just slap a function on individual links that would call window.open.
ReplyDeleteUpdated the post with a jQuery solution from http://www.badlydrawntoy.com/2009/03/03/replacing-target_blank-for-strict-xhtml-using-jquery-redux/.
ReplyDeleteFixed the outer double-quotes in the jQuery code. It works great.
ReplyDelete