JavaScript File Selection Simulation

By | April 12, 2011

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

  1. Link the js file to your page.
  2. <script type="text/javascript" src="file_selection_simulation.js"></script>
  3. Create HTML elements.
  4. <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>
  5. Add some style.
  6. <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>
  7. Initialize the fileSelectManager instance.
<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.

clip_image002

Finally, the script will set the selected file name to the trigger:

clip_image004

Demo Download

Click here to download the full working sample. Smile