Quick Tip: Dynamically add an icon for external links

A common feature I've seen on “web 2.0” sites and wikis is the "external link" icon: . While I'm not crazy about the idea of sticking these little images all over the HTML, they're a great candidate for using progressive enhancement. In our case, we can use jQuery to add the images pretty easily.

Test the hostname

To identify the external links, we test for the location.hostname against the link's hostname, which will be represented by this.hostname once we have the selector in place, and make sure the two don't match. We should also test for the mere existence of this.hostname to avoid problems or false positives with "mailto" links. our tests will look like this: this.hostname && location.hostname !== this.hostname.

Use the filter function

Now let's wrap that test in a filter function. For our example, we'll test all links inside an "extlinks" element that match the above test. Here is what it looks like:

[js]$(document).ready(function() { $('#extlinks a').filter(function() { return this.hostname && this.hostname !== location.hostname; }).after(' '); }); [/js]

A $(document).ready() is wrapped around the script so that it will execute when the DOM has loaded. Line 4 shows the insertion of the image after each of the external links.

Demo

Here is a little demo using the above code. Of the three links, only the second points to a different site. We should see the external-link icon next to it.

So, that's it. Short and sweet.



Responsive Menu
Add more content here...