How to style html file input with css and javascript
Posted By : Arun Kumar | 19-Dec-2014
Input type "file" is one of the most used form element,almost every website has it and has annoyed many amateur web designers including me.As shown in above picture what ever you try you will get that same old style buttons and text on every browser.So lets use some hack made in pure css and little bit javascript.
Lets get it started !
The html code :
<input id="uploadFile" placeholder="Choose File" disabled="disabled" /> <div class="fileUpload btn btn-primary"> <span>Upload</span> <input id="uploadBtn" type="file" class="upload" /> </div>
The first element which is input with the id of "uploadFile" is just a disabled input field which we are going to use to show the name of the uploaded file and before upload process it will show "choose file" which is set as placeholder.
The magic resides in the next element which is a div with class "fileUpload" and "btn btn-primary" is class from twitter bootstrap which is for styling buttons.We have placed input type="file" inside this div with class name "upload".
The CSS magic !
.fileUpload { position: relative; overflow: hidden; margin: 10px; } .fileUpload input.upload { position: absolute; top: 0; right: 0; margin: 0; padding: 0; font-size: 20px; cursor: pointer; opacity: 0; filter: alpha(opacity=0); }
Now with in the css we have made file input field invisible be setting its opacity to 0 but it is actuall there.So, when this div gets clicked that file input field also gets clicked and the fileupload action gets triggered.
The Javascript
Whats left is show user the name of the uploaded file.We are going to print the uploaded file name on that disabled input field using javascript.
document.getElementById("uploadBtn").onchange = function () { document.getElementById("uploadFile").value = this.value; };
Thats it !
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Arun Kumar
Arun is a creative UI Developer