jQuery Link Target Automation

July 26th, 2010

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.

Link Targets, Web Standards, and jQuery

November 14th, 2008

As you may or may not be aware, XHTML 1.0 Strict does not include the old “target” attribute of a link. In other words, you can no longer code thusly in order to tell the client browser that you’d like the clicked link to open in a new window:

<a href="http://some.domain" target="_blank">Clicky!</a>

So what does one do if you still want to open a link in a new window while still maintaining the integrity of your XHTML document? There have been many proposed solutions to this, but they basically devolve to two basic theories: 1) Use javascript to make it work; and 2) Extend the DTD to reinclude the old target attribute. I tend to agree more with using javascript to make it work. Please don’t misunderstand. In an ideal world, extending the DTD would be awesome. Afterall, extensibility is part and partial to the whole XHTML idea. But in practice, I fear this would introduce too many interoperability issues between browsers.

Read the rest of this entry »