Home / Add an offsite link icon after external links with jQuery

Add an offsite link icon after external links with jQuery

Yesterday I posted how to add an offsite link icon after external links with CSS and in this post look at how to do the same thing but with jQuery instead of CSS. This allows the offsite links to appear in Internet Explorer 6 because the a[href^="http://"] type selector is not supported in IE6.

By implementing both methods in your web page you can support when Javascript is disabled in the browser (with the CSS) and support IE6 when Javascript is enabled (using the method below).

Add the following to your CSS, making whatever changes you want for the padding etc and supplying your own image:

a.external {
    background: url(/images/external.png) center right no-repeat;
    padding-right: 13px;
}

And then in your $(document).ready section add the following:

$("a").filter(function() {
    return this.hostname && this.hostname !== location.hostname;
}).addClass('external');

This will then add a external link icon icon after all the offsite links in your web page.

To see the code in action click the button below. The icon will appear after the first link only after the button. This will not work if you are viewing this in a feed reader etc so please click through to view this article in a web browser.

This link is an external link to http://www.google.co.nz
This link is a relative link to this article /add-offsite-link-icon-after-external-links-jquery/
This link is an absolute link to this article https://electrictoolbox.com/add-offsite-link-icon-after-external-links-jquery/

Simple, huh?