To detect cancellation can be a bit messy depending on what you are trying to do. If all you need is to prevent your code from in example clearing a stored list of files if the user accidentally opens the file dialogue again and closes it, you can listen to the 'change'
event and check if event.target.files.length
is larger than 0, or in other words that files has been provided, and then do what you want to do within that if statement.
If you want to do something specific on the user cancelling the file dialogue, you need to listen to both the 'change'
and 'cancel'
events. The reason for this is a quirk in how these events work. If no file was previously selected, then the 'change'
event will not trigger on closing the dialogue, instead the 'cancel'
event triggers. However, if there were files previously selected and the dialogue is closed, the 'cancel'
event doesn't trigger and now the 'change'
event takes a turn. If you open and close the dialogue one more time, the 'cancel'
event will resume triggering. Oh, and it will fire if the same exact files are selected again, but the 'change'
event won't. Because of course.
You can play around with the code snippet below by opening the dialogue, then closing it right away, only the 'cancel'
event will trigger. Open it again and select one or more files to trigger the 'change'
event, then open the dialogue again and close it and it will trigger once more. Open and close it again, and the 'cancel'
event triggers. Open it and select one or more files to trigger the 'change'
event, then open it and select the same exact files again to trigger the 'cancel'
event.
Hopefully that can help give an understanding of how the two events work in relation to one another.
const fileSelector = document.getElementById('file-selector');
fileSelector.addEventListener('change', (event) => {
/* Only do something as long as files has been selected. */
if (event.target.files.length > 0) {
/*
Do what you want to do if files are supplied
*/
let sOR = (event.target.files.length > 1) ? "s" : "";
console.log("File" + sOR + " selected.");
} else {
/*
Do what you want to do if no files are supplied or
just remove the else statement if you have no code to run
*/
console.log("No files selected, so user has selected to Cancel.");
}
});
/*
The 'cancel' event fires if the file dialogue previously didn't have files provided
and the user closed it, or if the user provides the same exact file(s)
*/
fileSelector.addEventListener('cancel', (event) => {
console.log("Same files were selected or user has selected to Cancel.");
});
<input type="file" id="file-selector" multiple>
.change()
is not executed by all browsers, should look for the event that is called. Are their browsers you are looking to work with specifically? – Jesseltonconfirm()
orprompt()
. – Jesselton