23 Oct

How to add attractive ‘file type’ icons on your webpage using jQuery

Best Practices, jQuery

Many times we need to show different icons for different files - mostly when files are being uploaded from various members.
Here's what we are trying to do:

Normally, it can be done with PHP, i.e. assign CSS classes dynamically, but that is way too inefficient after jQuery showed me the new method.
So, how to do it with jQuery ?

Given this snippet:

HTML:
  1. <div class="attachment"><a href="http://www.gigapromoters.com/blog/file.doc">mydocument.doc</a> <a href="http://www.gigapromoters.com/blog/file.pdf">mypdf.pdf</a> <a href="http://www.gigapromoters.com/blog/file.png">myimage.png</a> <a href="http://www.gigapromoters.com/blog/file.txt">mytext.txt</a></div>

1. Lets define CSS, and put icons in required directory.
Here's the css which I'll be using:

CSS:
  1. div.attachment a
  2. {
  3. color: black;
  4. font-weight: bold;
  5. padding-left: 32px;
  6. display: block;
  7. height: 25px;
  8. padding-top: 6px;
  9.  
  10. }
  11. .pdf
  12. {
  13. background: url('pdf.png') no-repeat;
  14. background-position: 5px 50%;
  15. }
  16. .doc
  17. {
  18. background: url('doc.gif') no-repeat;
  19. background-position: 5px 50%;
  20. }
  21. .txt
  22. {
  23. background: url('text.gif') no-repeat;
  24. background-position: 5px 50%;
  25. }
  26. .img
  27. {
  28. background: url('img.png') no-repeat;
  29. background-position: 5px 50%;
  30. }

2. Now, we need to write Javascript using jQuery so our files get their respective class names in order to assign different icon for different file types.

$('div.attachment a[@href$=pdf]').attr('class','pdf');

using selector to find all the 'a' tags where attribute 'href' end with 'pdf'.. simple enough ? as soon as selector does it work and return the matched elements, we assign to 'class' attribute, the value 'pdf'.. and done..! So, we can complete this for the rest of file types.

JavaScript:
  1. $(document).ready(function() {  //as soon as jQuery is initialized after page load
  2.  
  3. $('div.attachment a[@href$=pdf]').attr('class','pdf');
  4. $('div.attachment a[@href$=doc]').attr('class','doc');
  5. $('div.attachment a[@href$=txt]').attr('class','txt');
  6. $('div.attachment a[@href$=png]').attr('class','img');
  7. }

Here's the demo

$('div.attachment a[@href$=png]').attr('class','img');

This can improved to support multiple file types like jpg, jpeg and others, but I didnt go into much depth... If anyone already knows, I would love to see that trick.

- Abhimanyu Grover

Leave A Reply







Hire us

Contact us to get a free quote on your project.