$.ready(), to be executed when the document is ready to be manipulated, but I’ve left that part out here for brevity.
Round 1: Because jQuery supports CSS1-3, you can mimic the CSS rule that wouldn’t work in IE6:
1 2 3 4 5 6 7 8
Round 2: You could do one of these snippets for each file type, but with jQuery, you can take advantage of the $.each() utility method to do a loop, eliminating redundant code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Round 3: One problem with this: while jQuery does support these attribute selectors, in my experience they require some pretty heavy lifting to do the pattern matching, which can slow things down significantly. Since the method above would require multiple selections (one for each extension/image combination), it makes sense to try a different way that will require fewer selections and less pattern matching:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
And in fact, in limited testing using Firebug, this second version is faster than the first if you have more than two filetypes (and thus more than two selections).
Taking it further
You can also add a different icon to external links, and only add filetype icons to internal links:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
Or, only add icons to certain links, like a list of files in an unordered list, by changing your selector from
- There are nuances to the CSS you’ll want to apply to your links; the above is just an example of something that may or may not work for you. Read more here about how to style the links so your background images appear as you want them to.
- If you’re using transparent PNGs for your background images, iepngfix will save the day.
- famfamfam has some great icons available for free under the Creative Commons Attribution 2.5 License.