Wednesday, 19 September 2018

Programmatically generated/activated file input doesn't always fire `input` event

I have a button on my web application, which has the following code in the click event handler:

const fileInputEl = document.createElement('input');
fileInputEl.type = 'file';
fileInputEl.accept = 'image/*';

fileInputEl.addEventListener('input', (e) => {
  if (!e.target.files.length) {
    return;
  }

  // Handle files here...
});  

fileInputEl.dispatchEvent(new MouseEvent('click'));

Sometimes (about 1 out of 8), after selecting the file, the input event doesn't fire after choosing a file. I'm guessing this is a browser bug around the lifecycle of the element.

Any way around this short of appending the element to the page and removing it later? What's the proper way to handle this in modern browsers these days?

I'm testing with Google Chrome on Windows.

JSFiddle: http://jsfiddle.net/pja1d5om/2/



from Programmatically generated/activated file input doesn't always fire `input` event

No comments:

Post a Comment