Today we are customizing a file upload button using CSS3, HTML5 and Javascript . If you have ever tried this earlier then you would know customizing a file upload button is very difficult. Now, I am going to try and explain the process to you in a simpler way.
So, take a look at how we customize a file upload button.
Here, we are creating a new file upload button on image icon which behaves consistently in pure “css cross browser”.
And here we begin with:
Step 1: index.html
The only HTML5 feature is the “multiple” attribute which allows the user to select any number of files.
The HTML markup is pretty simple, we just want to create a button which can be placed anywhere in the form:
<div class="fileUpload"> <span class="custom-span">+</span> <p class="custom-para">Add Images</p> <input id="uploadBtn" type="file" class="upload" /> </div> <input id="uploadFile" placeholder="0 files selected" disabled="disabled" />
In the code above, at first we make two input tags with id. One of them will be “uploadBtn” which is used to upload the file, and other will be “uploadFile” which is actually used to display the name of the image being uploaded.
Step 2: CSS included
While we are in the CSS, let’s just style our custom file upload button:
.fileUpload { position: relative; overflow: hidden; margin: 10px; background-color: #BDBDBD; height: 200px; width: 200px; text-align: center; } .fileUpload input.upload { position: absolute; top: 0; right: 0; margin: 0; padding: 0; font-size: 20px; cursor: pointer; opacity: 0; filter: alpha(opacity=0); height: 100%; text-align: center; } .custom-span{ font-family: Arial; font-weight: bold;font-size: 100px; color: #FE57A1} #uploadFile{border: none;margin-left: 10px; width: 200px;} .custom-para{font-family: arial;font-weight: bold;font-size: 24px; color:#585858;}
Now, you can use any type of a styling without worrying how to change default styles. In the CSS part, we need to define the dimensions-width and height-of the button as well as background and style the button text. In the above code, we have to used a class named “fileUpload” which actually sets the position of the “div” to “relative” (means it’ll work within the entire div section and not at the position where the file upload tag is used ). So, use this one to build your custom file upload button.
Step 3: Javascript
<script type="text/javascript"> document.getElementById("uploadBtn").onchange = function () { document.getElementById("uploadFile").value = this.value; }; </script>
Using this script, we display the name of the images being uploaded by user in the textbox. Make sure you add the appropriate javascript in with the button to make it call the function.
For any doubts and queries, feel free to leave comments below. Remember to subscribe to our newsletter. Do share the tutorial if you think it’s worth it.
Happy Reading!