I'm playing with JavaScript and wrote simple function that creates INPUT
element (type="file"
) and simulates click.
var createAndCallFileSelect = function () {
var input = document.createElement ("input");
input.setAttribute ("type", "file");
input.addEventListener ("change", function () {
console.log (this.files);
}, false);
input.click();
}
It works great most of time but sometimes it doesn't fire onChange
event when file is selected (or more files when used with multiple
attribute on INPUT
).
I know that onChange
won't fire when you re-select same file but clearly this is not the case here. It doesn't fire an event only first time I use this function, and sometimes only. Every next click normally fires onChange
if something is selected from dialog.
Already tried searching for this problem here and around but seems that all onChange problems and solutions are related to famous problem with re-selecting same file again.
I found this happens on latest Opera and Firefox, never tested with other browsers. Also. I tried to wait entire page to be loaded but result is still the same - sometimes it doesn't trigger onChange
on first call.
Can anyone explain to me why this happens? I already have workaround code, that's not the question, just need explanation of why this happens when INPUT is created and called this way.
Update:
Cascade delay
var function createAndCallFileSelect = function () {
var input = document.createElement ("input");
setTimeout (function () { // set type with 1s delay
input.setAttribute ("type", "file");
setTimeout (function () { // attach event with 1s delay
input.addEventListener ("change", function () {
console.log (this.files);
}, false);
setTimeout (function () { // simulate click with 1s delay
input.click();
}, 1000);
}, 1000);
}, 1000);
}
This also doesn't work. I tried to delay execution of each line to be sure that everything is executed in right order. 3 seconds after call it opens file-select dialog but again, sometimes it doesn't fire onChange
event after file is selected.