Styling a file upload control or input type = “file”


FileUpload control has weird styles, especially when you view them across browsers. The normal look and feel of the control, would look like something below:

The Safari one looks really worth a bug for the testers.

This solution to style fileupload controls is a concise and verified version of the solution by Michael McGrady.

Step 1 : Copy the following code to you javascript file that loads along with the page.

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=’search.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;
}
}
}

Step 2 : Add the initiFileUploads function to the onload event of the body. You must have your file upload control to be styled, placed on the page. The javascript will handle the styling of the controls of type file input.

<body onload=”initFileUploads()”>
<div>
<input type=”file” />
</div>
</body>

Step 3 : Add the following CSS class to your css.

div.fileinputs {
position: relative;
}

div.fakefile {
position: absolute;
top: 0px;
left: 0px;
z-index: 1;
}

input.file {
position: relative;
text-align: right;
-moz-opacity:0 ;
filter:alpha(opacity: 0);
opacity: 0;
z-index: 2;
}

Step 4 : Sit back and enjoy!!!

The output would look like something below:Images I used:

In case you want to get into the technical details of this styling, i strongly recommend you to visit Quirks Mode input styling.

Try to style the textboxes with one of these shared images, your file upload control will look cool.

By the way, It is browser independent, but javascript dependent.

Even if your javascript fails, your original upload control stays there. So don’t worry much about the functionality, in case javascript is disabled.

Feel free to leave a reply here...

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s