PinoyTech.org

CodeIgniter, Kohana, Mootools, jQuery and CSS

Add Icons to External Links with Mootools and CSS

Posted by teejay on November 17, 2009

A trend going on around on websites are putting icons on links that point to web pages externally. If you want that on your site, this simple script will dynamically take care of that for you with the help of Mootools, a compact Javascript Framework and some CSS.

Javascript

window.addEvent('domready',function() {
 $$('a').each(function(link) {
  if(link.hostname != window.location.host) {
   link.addClass('external');
  }
 });
});

CSS

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

You can copy and paste the Javascript and CSS above. Just make sure that you point the .external rule to point the background to the correct external icon.

View the demo

Categories: How To, Web Development

Tags: javascript, mootools

6 Comments

Royal

That’s a neat trick. Thanks for sharing this Mootools tip.

November 17th 2009

Mario

I found this site through catswhocode.com. Nice site. Nice tutorials.

December 1st 2009

Jason Huebel

Anybody have an example based on jQuery?

December 26th 2009

Taylor Satula

Or you could do it without mootools like this. But great tut anyway

a[icon ^=“out”] {
  padding-right: 20px;
  background: transparent url(/external.gif) no-repeat center right;
}

March 2nd 2010

jerone

If you need more link detection, check out this script: http://jeroenvanwarmerdam.nl/content/resources/javascript/jquery/linkalert/linkalert.aspx

March 29th 2010

ken the tech

why to use js when you can just add style to a? If you don’t want to add background image too all links on the website you can just create a.class and add padding-right and background-image to them. Am I right?

May 10th 2010

Comments are not allowed