Context
The build-in file selection elements of browsers are ugly and cannot be customized easily.
If developer need to change the appearance of the file selection element, it’s almost impossible because of some security issues. So I wrote this script to simulate the file input selection by javascript so that the end user can click upon an image to open the dialog, and the image button can be customized to any of style.
Compatiblity
Tested in IE6, IE7, IE8, Firefox4, Chrome10.
Use the script
- Link the js file to your page.
- Create HTML elements.
- Add some style.
- Initialize the fileSelectManager instance.
<script type="text/javascript" src="file_selection_simulation.js"></script>
<div style="position:relative;width:102px;height:29px;"> <input id="file_trigger" class="file-trigger" type="button" value="Select File..." /> <div id="real_file_container" class="file-container"><input id="real_file" type="file" class="real-file"/></div> </div>
<style type="text/css"> .file-container{ width:18px; height:20px; overflow:hidden; position:absolute; filter:alpha(opacity=0); opacity: 0; top:0; left:0; } .real-file{ margin-left:-150px; } /*the trigger normally should be customized*/ .file-trigger{ background-image:url(button.jpg); border:0; width:102px; height:29px; color:white; } </style>
<script type="text/javascript"> var fManager = new _smt.fileSelectManager( 'file_trigger', 'real_file_container', 'real_file'); fManager.init(); </script>
Result
The script will attach event handler function to the trigger and file container element. The effect is, when the end user move his mouse over the trigger, the file container will move to right under the mouse position. If the user click his mouse, he is clicking the file selection element actually.
Finally, the script will set the selected file name to the trigger:
Demo Download
Click here to download the full working sample.