Add icons to your links automatically using jQuery & CSS

You want to show a particular icon to a particular type of link. For eg: a pdf icon to all pdf file links, a text document icon to all text document links, zip icon to all links that are linked to zip files etc.

Step 1 – Find the right icons

Getting a free icon describing your file type is easy. You might need to search for free icon sets, or better search in any of the three following icon search engines. For eg: search for the term “pdf” and you will see a lot of images in different dimensions, select the one that suits your need. Just make sure you’re not using a copyrighted icon 🙂

  • Icon Look – http://www.iconlook.com
  • Icon Let – http://www.iconlet.com
  • Icon Finder – http:www.iconfinder.net

CSS styles

Now we’ve have the right icons. Now we need to add classes with background image.

a.pdf { /*The background image*/
  background: url(images/pdf.png) no-repeat left center;
  padding-left: 20px;
  line-height: 16px; /* To center the text vertically with the icon */
}

a.txt { /*The background image*/
  background: url(images/txt.png) no-repeat left center;
  padding-left: 20px;
  line-height: 16px;
}

a.zip { /*The background image*/
  background: url(images/zip.png) no-repeat left center;
  padding-left: 20px;
  line-height: 16px;
}

a.email {
  background: url(images/email.png) no-repeat left center;
  padding-left: 20px;
  line-height: 16px;
}

a.external {
  background: url(images/ext_link.png) no-repeat left center;
  padding-left: 20px;
  line-height: 16px;
}

Eg:

.download a.zip { /*The background image*/
  background: url(images/zip.png) no-repeat left center;
  height: 48px;
  padding-left: 55px;
  line-height: 48px; /* Center the text vertically with image */
  vertical-align: bottom; /* to align the text with image bottom, line height property required */
  display: block; /* Need this to show the images fully */
  float: left; /* You might need this as well for aligning it with the parent element */
}

JQuery

Now, we can write the jQuery statements.

More info http://cool-javascripts.com/jquery/add-icons-to-your-links-automatically-using-jquery-css.html

Leave a Reply