Trishul Goel

Handle Cancel Click on File Input

March 01, 2017

Ever Tried capturing cancel event on Browse file input type in HTML, tbh there is no direct way to do so :(

But there is a workaround adding a bit of javascript. We can play with onfocus event of the BODY element. File input

Example -> HTML

<input type='file' id='theFile' onclick="initialize()" />


var theFile = document.getElementById('theFile');
function initialize()
    document.body.onfocus = checkIt;
function checkIt()
      alert('Files Loaded');
      alert('Cancel clicked');
    document.body.onfocus = null;

See it working here.

Trishul is a professional frontend developer; writes React code for living and volunteers for Mozilla to justify his existence. He promotes PWAs to developers #teamWeb. He loves to talk about modern Javascript and tries to use it to solve all of his problems, even the domestic ones. He is an expert in developing PWAs and browser extensions.