I need to set the files of a file upload to files that the user dropped and then trigger a change event on the file upload.
window.addEventListener("drop", (e) => {
e.preventDefault();
fileUpload.files = e.dataTransfer.files; // change event only fires in safari
fileUpload.dispatchEvent(new Event("change"));
});
The code above sets the files of the file upload to the dropped files. Firefox and Chrome do not fire a change event when setting the fileUpload.files property. Safari however does.
This results in the change event being fired twice in Safari, which triggers code in the change event handler twice.
I also tired using the input event instead of the change event, which results in the same behavior.
I would like to avoid browser detection to solve this issue. I am looking for a general solution that works even if Chrome or Firefox were to adopt Safari's behavior.
What is the correct behavior in this case? Safari's or Chrome's?
Is there an elegant solution to only fire one change event that doesn't use media query hacks or other browser detection methods?