Open file dialog box in JavaScript
$("#logo").css('opacity','0');
$("#select_logo").click(function(e){
e.preventDefault();
$("#logo").trigger('click');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" id="select_logo">Select Logo</a> <input type="file" id="logo">
for IE add this:
$("#logo").css('filter','alpha(opacity = 0');
Here is a nice one
Fine Uploader demo
It is an <input type='file' />
control itself. But a div is placed over that and css styles are applied to get that feel. Opacity of the file control is set to 0 so that it appears that the dialog window is opened when clicking on the div.
Actually, you don't need all that stuff with opacity, visibility, <input>
styling, etc. Just take a look:
<a href="#">Just click me.</a>
<script type="text/javascript">
$("a").click(function() {
// creating input on-the-fly
var input = $(document.createElement("input"));
input.attr("type", "file");
// add onchange handler if you wish to get the file :)
input.trigger("click"); // opening dialog
return false; // avoiding navigation
});
</script>
Demo on jsFiddle. Tested in Chrome 30.0 and Firefox 24.0. Didn't work in Opera 12.16, however.
I dont't know why nobody has pointed this out but here's is a way of doing it without any Javascript and it's also compatible with any browser.
EDIT: In Safari, the input
gets disabled when hidden with display: none
. A better approach would be to use position: fixed; top: -100em
.
EDIT 2: A different approach would be to use opacity: 0
. The problem is that it can mess with the layout. I added some CSS to the example to illustrate the problem.
label {
display: inline-block;
background: #ddd;
border: 1px outset #ccc;
border-radius: .3em;
padding: .3em 1em;
margin: .5em;
}
label:active {
border-style: inset;
}
<label>
Using <code>position: fixed</code>
<input type="file" style="position: fixed; top: -100%">
</label>
<label>
Using <code>opacity: 0</code>
<input type="file" style="opacity: 0">
</label>
If you prefer you can go the "correct way" by using for
in the label
pointing to the id
of the input like this:
<label for="inputId">file dialog</label>
<input id="inputId" type="file" style="position: fixed; top: -100em">