Add an offsite link icon after external links with jQuery
Posted March 28th, 2009 in Javascript
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
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 http://www.electrictoolbox.com/add-offsite-link-icon-after-external-links-jquery/
Simple, huh?
Related posts:
- Get the total number of matched elements with jQuery (Tuesday, March 31st 2009)
- Add an offsite link icon after external links with CSS (Friday, March 27th 2009)
- Use jQuery to make all offsite links open in a new window (Tuesday, March 24th 2009)
- jQuery's document ready initialization (Friday, February 20th 2009)

Comments
blog comments powered by Disqus