Spry LogoThis is the first bit of code that I have created that I think is good enough to share. I didn’t come up with this on my own, I drew inspiration from this blog post, and had some help from V1 over at the Adobe Spry Forum.

This simple bit of JavaScript will give your external links on your page an icon to indicate that you will be leaving the site. I previously would have done this using a CSS selector that targeted all links in a paragraph that had the target attribute set to “_blank”, but I wanted a fool-proof way of doing this without having to remember to set the target.

How does it work?

It works by manipulating the DOM using the Spry Dom Utils JS. It creates an observer that on page load adds the class called “external” to all links that are on a different domain.

To use it, just put this in your head section:

<script src="SpryAssets/SpryDOMUtils.js" type="text/javascript"></script>
<script src="SpryAssets/SpryExternalLinkIcon.js" type="text/javascript"></script>
<link href="SpryAssets/SpryExternalLinkIcon.css" rel="stylesheet" type="text/css" />

The first file is from the current Spry library.

The second is my custom code, and the third is a small bit of CSS.

This is SpryExternalLinkIcon.js:

function externalLinkIcon(){
  Spry.$$("a").forEach(function(href) {
  	if( href.hostname != window.location.host ){
  Spry.Utils.addClassName( href, 'external');}
  });
}
Spry.Utils.addLoadListener(externalLinkIcon);

This is SpryExternalLinkIcon.css

.external {
    background: url('external.png') 100% 60% no-repeat;
    padding:  0 15px 0 0;
}

Now any link that is on a different domain will get assigned the class “external”, which in turns puts an external link icon at the end of it.

Demo

You can see what I have been talking about here: http://www.dooza.tv/spry/SpryExternalLinkIcon.html

Download

You can download the files here: http://www.dooza.tv/spry/SpryExternalLinkIcon.zip

Conclusion

Using JavaScript to add this icon is progressive enhancement, the page doesn’t break, the link still works, but in browsers with JavaScript support you get the added functionality of an icon that helps the visitor recognise an external link. The visitor might want to open the link in another tab or window, knowing its an external link before having to click it will save time.

I would love to hear your opinions on this little bit of code that I have presented here. There aren’t many Spry tutorials or blogs about, which is a shame, its got potential.