I\'d like to make a click event fire on an tag programmatically.
Just calling click() doesn\'t seem to do anything or at lea
It works :
For security reasons on Firefox and Opera, you can't fire the click on file input, but you can simulate with MouseEvents :
<script>
click=function(element){
if(element!=null){
try {element.click();}
catch(e) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click",true,true,window,0,0,0,0,0,false,false,false,false,0,null);
element.dispatchEvent(evt);
}
}
};
</script>
<input type="button" value="upload" onclick="click(document.getElementById('inputFile'));"><input type="file" id="inputFile" style="display:none">
I found that if input(file) is outside form, then firing click event invokes file dialog.
JS Fiddle: http://jsfiddle.net/eyedean/1bw357kw/
popFileSelector = function() {
var el = document.getElementById("fileElem");
if (el) {
el.click();
}
};
window.popRightAway = function() {
document.getElementById('log').innerHTML += 'I am right away!<br />';
popFileSelector();
};
window.popWithDelay = function() {
document.getElementById('log').innerHTML += 'I am gonna delay!<br />';
window.setTimeout(function() {
document.getElementById('log').innerHTML += 'I was delayed!<br />';
popFileSelector();
}, 1000);
};
<body>
<form>
<input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)" />
</form>
<a onclick="popRightAway()" href="#">Pop Now</a>
<br />
<a onclick="popWithDelay()" href="#">Pop With 1 Second Delay</a>
<div id="log">Log: <br /></div>
</body>
THIS IS POSSIBLE: Under FF4+, Opera ?, Chrome: but:
inputElement.click()
should be called from user action context! (not script execution context)
<input type="file" />
should be visible (inputElement.style.display !== 'none'
) (you can hide it with visibility or something other, but not "display" property)