Explain Codes LogoExplain Codes Logo

How to detect when cancel is clicked on file input?

javascript
prompt-engineering
event-listeners
file-system-access-api
Alex KataevbyAlex Kataev·Feb 16, 2025
TLDR

Recognize a file input's cancel click through checking for an empty files attribute upon a change event:

document.querySelector('input[type="file"]').addEventListener('change', event => { if (!event.target.files.length) console.log('Cancel clicked...or ghost?'); });

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:

let fileInput = document.querySelector('input[type="file"]'); let hadFocus = false; fileInput.addEventListener('focus', () => { hadFocus = true; // Like gaining 'the force' }); fileInput.addEventListener('blur', () => { if (hadFocus && !fileInput.value) { console.log('Cancel imminent! Red Alert!'); } hadFocus = false; // 'The force' is lost });

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:

if ('showOpenFilePicker' in window) { try { const [fileHandle] = await window.showOpenFilePicker(); // Like opening a mysterious box // Process the chosen file here } catch (e) { if (e.name === 'AbortError') { console.log('Cancel encountered! Abort mission!'); } } }

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 and touchend.
  • 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 every focus.

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 an focus 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.