In a post I wrote back in November 2008, I taught you how jQuery can be used to make links open in a new window in a standards compliant way, using the “rel” attribute in your link tag. In my efforts to build and run a photography news website recently, it quickly became clear that I didn’t want to mark all my external links with “rel=external” , because every single post has an external link. Being thusly motivated, I started looking for wordpress plugins that would scan the link, determine if it was external, and do something to it in a standards compliant way that would make it open in a new window. Coming up with diddly-squat on the search, I realized I was being dense. Again. I could let jQuery do that for me, and not have to install a plugin to do it. Here’s the relevant code:
<script type="text/javascript">
$(function() {
$("a:not([href^='http://www.phototimes.net'])").attr("target", "_blank").addClass("external-link");
});
</script>
This little snippet does several things all at once. The first thing it does is find all links whose href attribute does not begin with http://www.phototimes.net. This selects links that are off-domain, which we want to open in a new window. The next part sets the target attribute of the link to _blank, so that it will open in a new window, and the third part adds the external-link class to the tag. The external-link class allows us to style the link differently that other links on the site, like adding one of those nifty little arrows that visually indicate that the link is offsite, and was popularized by Wikipedia. jQuery, I think I love you.