Styling an input type=”file” using jQuery

August 21st, 2008 | by David |

During the last days I had to work on some forms that are using file upload inputs. I wondered how to make the file input fields look nicer (they are not affected very much by css) and found this appealing solution. Since the application needs JavaScript anyway, there was nothing wrong with the approach and it worked fine. However, I didn’t like the look of the (working!) JavaScript code and wanted to do it more niftily using jQuery.

This is how the original code looks like:

var W3CDOM = (document.createElement && document.getElementsByTagName);
 
function initFileUploads() {
	if (!W3CDOM) return;
	var fakeFileUpload = document.createElement('div');
	fakeFileUpload.className = 'fakefile';
	fakeFileUpload.appendChild(document.createElement('input'));
	var image = document.createElement('img');
	image.src='pix/button_select.gif';
	fakeFileUpload.appendChild(image);
	var x = document.getElementsByTagName('input');
	for (var i=0;i<x.length;i++) {
		if (x[i].type != 'file') continue;
		if (x[i].parentNode.className != 'fileinputs') continue;
		x[i].className = 'file hidden';
		var clone = fakeFileUpload.cloneNode(true);
		x[i].parentNode.appendChild(clone);
		x[i].relatedElement = clone.getElementsByTagName('input')[0];
		x[i].onchange = x[i].onmouseout = function () {
			this.relatedElement.value = this.value;
		}
	}
}

As I said before it works fine, but it is… well… clumsy. I like the clean and efficient approach of JavaScript using the jQuery library and this is why I went for this replacement:

$('input[type=file]').each(function(){
  $(this).addClass('file').addClass('hidden');
  $(this).parent().append($('<div class="fakefile" />').append($('<input type="text" />').attr('id',$(this).attr('id')+'__fake')).append($('<img src="pix/button_select.gif" alt="" />')));
 
  $(this).bind('change', function() {
    $('#'+$(this).attr('id')+'__fake').val($(this).val());;
  });
  $(this).bind('mouseout', function() {
    $('#'+$(this).attr('id')+'__fake').val($(this).val());;
  });
});

Instead of selecting the newly generated input field by its tag name, I decided to give it the same ID as the original field plus ‘__fake’ appended – if you have any field with the same name, just change the postfix to something else. This makes the addressing in the event handler functions easier.

Of course this code should be executed after the document is fully loaded, this is why it goes into another block:

$(document).ready(function() {
  $('input[type=file]').each(function(){
    $(this).addClass('file').addClass('hidden');
    $(this).parent().append($('<div class="fakefile" />').append($('<input type="text" />').attr('id',$(this).attr('id')+'__fake')).append($('<img src="pix/button_select.gif" alt="" />')));
 
    $(this).bind('change', function() {
      $('#'+$(this).attr('id')+'__fake').val($(this).val());;
    });
    $(this).bind('mouseout', function() {
      $('#'+$(this).attr('id')+'__fake').val($(this).val());;
    });
  });
});

Voilá! I like it more this way, especially because now it’s a lot easier to modify the behaviour of the script, e.g. if you only want to do it for some specific fields or if you want to add something other than an image as the button.
It’s your freedom of choice!

  1. 32 Responses to “Styling an input type=”file” using jQuery”

  2. By Hunts on Jul 31, 2009 | Reply

    How can create multiple “input file” fields in one page using this method.

  3. By David on Aug 1, 2009 | Reply

    This automatically converts all file inputs in the page.

  4. By ViX on Jun 17, 2010 | Reply

    Thanks for the idea and I will try it with my settings.

  5. By Josh on Oct 11, 2010 | Reply

    Why not..

    $(document).ready(function() {
    $(‘input[type=file]‘).each(function(){
    $(this).addClass(‘file’).addClass(‘hidden’);
    $(this).parent().append($(”).append($(”).attr(‘id’,$(this).attr(‘id’)+’__fake’)).append($(”)));

    $(this).bind(‘change mouseout’, function() {
    $(‘#’+$(this).attr(‘id’)+’__fake’).val($(this).val());;
    });

    });
    });

  6. By Phil on Apr 18, 2011 | Reply

    @JOSH:

    Did you try that ? I mean – why are you counteracting a functional usable piece of code with your – “why not?”-stuff.
    Well then I will tell why not:
    First – BECAUSE it DOES NOT work
    Second – Im not gonna debug your “Why not”-stuff to find out WHY NOT

  7. By Phil on Apr 18, 2011 | Reply

    @David – thx a lot ! – exactly what I was looking for -

  8. By try this site on Jun 10, 2013 | Reply

    Excellent write-up. I absolutely appreciate this site.
    Continue the good work!

  9. By guidetosmoothskin.com on Jun 15, 2013 | Reply

    Pretty nice post. I just stumbled upon your blog
    and wanted to say that I have truly enjoyed browsing your
    blog posts. In any case I will be subscribing to your rss feed and I hope
    you write again soon!

  10. By commodity future option trading on Jun 19, 2013 | Reply

    Excellent article. Keep posting such kind of info on your site.
    Im really impressed by it.
    Hey there, You’ve performed an excellent job. I will definitely digg it and for my part suggest to my friends. I am sure they’ll be benefited from this site.

  11. By trading in forex on Jun 20, 2013 | Reply

    What’s up, its nice paragraph about media print, we all know media is a fantastic source of data.

  12. By Jamaal on Jun 20, 2013 | Reply

    I am regular reader, how are you everybody? This
    post posted at this website is actually nice.

  13. By gold binary options on Jun 22, 2013 | Reply

    Its not my first time to visit this web site, i am browsing this web site dailly and get good data from here everyday.

  14. By projectnursery.com on Jul 1, 2013 | Reply

    Ahaa, its fastidious conversation on the topic of this article here at this website, I have read all that,
    so at this time me also commenting here.

  15. By free binary option trading signals on Jul 16, 2013 | Reply

    Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point.
    You definitely know what youre talking about, why waste your intelligence on just posting videos to
    your weblog when you could be giving us something enlightening to read?

  16. By trading stock options on Jul 19, 2013 | Reply

    I don’t even understand how I finished up here, but I believed this submit was once good. I do not realize who you’re however definitely you’re going to a famous blogger if you happen to are not already. Cheers!

  17. By musicbrainz.org on Jul 26, 2013 | Reply

    I’m not sure why but this web site is loading very slow for me. Is anyone else having this issue or is it a problem on my end? I’ll check back later and see if
    the problem still exists.

  18. By http://www.widgetbox.com/user/pantsdead4 on Aug 3, 2013 | Reply

    I enjoy what you guys tend to be up too. This kind of clever work and coverage!
    Keep up the good works guys I’ve added you guys to our blogroll.

  19. By Marcos on Aug 9, 2013 | Reply

    Heya just wanted to give you a quick heads up and let you know
    a few of the images aren’t loading properly. I’m not sure
    why but I think its a linking issue. I’ve tried it in two different browsers and both show the same outcome.

  20. By tool download on Sep 3, 2013 | Reply

    Put a check next to “Bit 0″ (comment’s suffix will change to “on”),
    and a check next to “Bit 1″. The people just want the stuff and can care less as
    to the legality of it all. Neopets does a good job of
    handling smaller situations on the fly but when there is a three day weekend or holiday the site is ripe for the picking where hackers,
    scammers and cheat programs are concerned.

  21. By Fickkontakte für Livesex Dates on Sep 3, 2013 | Reply

    I’ve been exploring for a bit for any high quality articles or blog posts in this kind of house .
    Exploring in Yahoo I finally stumbled upon this site. Reading this
    info So i’m glad to exhibit that I’ve a very good uncanny
    feeling I found out exactly what I needed. I so much without a doubt will make sure to do not
    forget this site and provides it a glance on
    a constant basis.

  22. By professionell Webdienstleistungen on Sep 24, 2013 | Reply

    Klasse gemachte Website, das Layout gefaellt mir echt gut!

    War bestimmt ne menge Arbeit.

  23. By hundeerziehung on Sep 26, 2013 | Reply

    Gute Webpage. Vielen Dank.

  24. By hosting Parnter on Sep 27, 2013 | Reply

    Ich wollte einfach einen netten Gruss da lassen. Bin gerade auf
    die Websiete gestossen.

  25. By Kendall on Oct 18, 2013 | Reply

    Thanks for sharing your thoughts about obama care. Regards

  26. By periodontal treatment in on Oct 26, 2013 | Reply

    Pretty great post. I just stumbled upon your blog and wished to
    mention that I have truly enjoyed browsing your weblog posts.
    In any case I’ll be subscribing in your feed and I am hoping you write again soon!

  27. By webpage on Nov 22, 2013 | Reply

    I’m curious to find out what blog platform you’re working with?

    I’m having some small security problems with my latest
    blog and I would like to find something more safe.
    Do you have any recommendations?

  28. By Harrison Powers on Jan 3, 2014 | Reply

    Thank goodness for this script. You rock David!

  29. By cadbury dresses UK on Jan 4, 2014 | Reply

    Hello, thank you. I love you!

  30. By nantucket wedding photographer on Mar 5, 2014 | Reply

    We’re a group of volunteers and starting a new scheme in our
    community. Your website offered us with valuable info to work on.
    You’ve done an impressive job and our entire community will be thankful to you.

  31. By Danilo da Silva on Mar 20, 2014 | Reply

    There is a problem with the size of the button image that varies from browser to browser and from language to language. If the height of the button image is greater than that of the Input element, undesirable results will occur.

  32. By oryginalna strona on Mar 28, 2014 | Reply

    Hello, just wanted to say, I liked this post.
    It was helpful. Keep on posting!

  33. By Christian Louboutin Toronto on Mar 30, 2014 | Reply

    Pretty great post. I just stumbled upon your weblog and wished to say
    that I’ve truly enjoyed surfing around your blog posts.

    After all I’ll be subscribing on your feed and I’m hoping
    you write again very soon!

Post a Comment