Glen Swinfield’s Website v2.0

“I work for Erskine Design in Nottingham. Which is nice. You've got choices, you can visit my homepage, take a look at the available downloads or view the blog archives. Please contact me whenever you like. Also, why not subscribe to the RSS feed.”

Automatically add a class the same as the file extension to a download link using jQuery

Just a very quick jQuery function that adds the file extension of a target file to a html anchor.

Download "Add File Class" function for jQuery v1.0.0

This is something that we needed for a recent project. I couldn’t find anything that did it already, but then I didn’t look that hard. Basically it finds the file extension of a target file in the href attribute of an anchor (link) and adds it as a class.

This basically enables specific styling depending on the type of file being linked to, for example a pdf or word doc icon.

You need to give your links a class that identifies them as linking to a downloadable file, the function assumes ‘file’ but you can change this if you wish. This has a secondary benefit of allowing you to apply default styling for people who have no Javascript enabled or as a sort of catch-all if you only want specific styling for a small number of file types.

You need to download and link the jQuery library for this to work. If you know a bit of jQuery you will have no trouble getting this to work, so I won’t waffle on. Suggestions for improvements are welcome.

Name:

Email:

URL:

Remember my personal information

Notify me of follow-up comments?

jQuery

Other Posts