How to detect when cancel is clicked on file input?
Recognize a file input's cancel click through checking for an empty files
attribute upon a change
event:
The cancel action results in no new file being chosen, leaving the files
attribute empty. Handy, right?
Employing focus events
Monitor the focus and blur events of the file input field to gauge when cancel may happen:
Like a Jedi using the force, it's all about feeling the disturbance (or lack of) when focus is lost — AKA cancel detected.
Leveraging File System Access API
Get fancy with the File System Access API for a more advanced, yet precise approach:
Ever had that fancy box that throws stuff at you when you don't carefully open it? That's what the showOpenFilePicker
does — it throws exceptions.
Addressing browser inconsistencies
Being mindful of cross-browser compatibility is crucial. Keep your users' different browsers in check:
- Zoning games: Encapsulate the file dialog with a clickable backdrop. Any click outside could hint a cancel operation.
- Prompt it right: A 'Confirm selection' text or icon goes a long way to ensure the user is satisfied with their choice.
- Enlist a fall-back: Make sure there's a 'clear selection' button besides the file input, covering all bases.
Handling special cases
Handling unique scenarios like mobile responsiveness and re-selection takes a touch of cleverness:
- Mobile warfare: Tap/touch interfaces introduce a new challenge. Cater for
touchstart
andtouchend
. - Deja Vu: If a user chooses the same file, the
change
event feels like it's in a time loop and won't fire. To fix the matrix, reset the input value at the start of everyfocus
.
Curating a wholesome solution
Why rely on one tactic when a few can team up?
- Focus & blur: Use as the basic defense layer. If it catches something, you're already halfway successful.
- Reinforce with change: Another event listener observing
change
just boosts your fortress. - Timeout the sneaky: Absence of
change
after some time (setTimeout
) despite anfocus
can suggest 'Operation Cancel'. - User direction: Guide users with clear actions, prompting selection confirm or cancel.
Iterating over user experience
If cancel detection is critical, rethink the user's journey:
- Clear prompts: Post-selection confirm buttons are your best bet.
- Active feedback: A UI toast or modal nudging the action feels connected and interactive.
Was this article helpful?