Sitemap / Advertise

Information



Tags



Share

How to customize a file input element in CSS and JavaScript

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement




Definition

If you want to take a different approach to your web project to improve the user experience, you can try re-design the default version of the file input element as I shall show you down below because a customized file input is not ubiquitous around the web.

Code

First of all, hide every file input in their parent labels in order to customize file inputs.

Create a new file input button using the before pseudo-class the hover pseudo-class.

In JavaScript, get the selected file name when the onchange function activated to display it. - .files.item(0).name gives you the whole name of selected file including the extension.

As you can see, I choose to use the querySelectorAll method to obtain element properties and therefore a multi-file-input function is optional for further usage.


// CSS //

input[type="file"]{color:white;width:0;height:0;}

.new-file-input:before{content:'Select Any File';color:white;background-color:#002699;background:linear-gradient(45deg, #1a53ff, #002699);font-size:15px;font-weight:bold;border-radius:5px;cursor:pointer;border:none;padding-left:10px;padding-right:10px;}
.new-file-input:hover:before{background-color:#cccccc;background:linear-gradient(45deg, #cccccc, #002699);transition:1s;}
.file-name{color:white;font-size:10px;font-weight:bold;}

//

// HTML //

<label class="new-file-input"><input type="file" name="file-input" class="file-input" /></label> <label class="file-name">None Selected!</label>

//

// JavaScript //

var file = document.querySelectorAll(".file-input");
var file_name = document.querySelectorAll(".file-name");

file[0].onchange = function(){
file_name[0].innerHTML = file[0].files.item(0).name;
};

//

Result: