Skip to main content

Tuesday, January 09, 2007

Adding CSS icons to links automatically

Many times, developers come across the need to link to "non-web" documents. This would include .pdf, .xls, .doc, etc... files. What has become a common theme is highlighting the hyperlink by adding an icon next to it showing the user what to expect. In other words, if the hyperlink goes to a .pdf, show a small .pdf icon next to the link.

This can be easily done with CSS through a class:

a.application-pdf {
    padding: 3px 18px 0px 0px;
    background: url(application-pdf.gif) bottom right no-repeat;
}

application-pdf.gif is a small icon. You can see how it looks at: http://admissions.unl.edu/diversity/nationalhispanicvisit.asp

This requires a class to be provided on the link:

<a href="xyz.pdf" class="application-pdf">The year-end financial report</a>.

This works great, but wouldn't it be better if we didn't have to put this class in every time we created a link to a .pdf?

Through CSS, you can use selectors to automatically add the icon image. I won't go into the details, the gurus over at Ask the CSS Guy have done that already. It looks like this:

a[href $='.pdf'] {
padding: 3px 18px 0px 0px;
background: url(application-pdf.gif) bottom right no-repeat;
}

However, this only works in IE7, Firefox and Safari. This leaves out a major population of IE6 and lower users who haven't upgraded (through my experience of IE7, I can't blame them). So I got to thinking, how can we make this better?

Enter jQuery. I love to find ways to use jQuery in my applications. When it comes to using Javascript, jQuery is the way to go!

What if we used jQuery to setup a rule to work only for IE6 and lower users that will add the icon? With that in mind, this is what I came up with:

$(document).ready(function() {
/*@cc_on
@if (@_jscript_build < 8832)
$("a[@href$='.pdf']").addClass("application-pdf");
/*@end
@*/
});

Basically what this does is determine if the broswer is IE6 (@_jscript_build < 8832), finds all links which end with ".pdf" and then add the "application-pdf" class to the A tag.

In the CSS, I have combined the use of the CSS selector and the original class definition:

a[href $='.pdf'], a.application-pdf {
padding: 3px 18px 0px 0px;
background: url(application-pdf.gif) bottom right no-repeat;
}
The same would work for any other document type, all we would need is another icon, the class definition and a line in the jQuery function.

With the combination of CSS and jQuery, we now an automatic way of adding icons next to each of our links to "non-web" documents. This won't work for user's without JavaScript, but it is still accessible. I figure I'll probably miss some .pdf links anyhow, so the payoff is about the same.

Posted By: Seth at 1:51:00 PM | comments (29) | Permalink | Trackback

jQueryWeb 2.0web design