itsopensource

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;
    console.log('initializing');
}
    
function checkIt()
{
    if(theFile.value.length) 
      alert('Files Loaded');
    else 
      alert('Cancel clicked');
    document.body.onfocus = null;
    console.log('checked');
}		

See it working here.

This blog was first published here


Trishul Goel

Trishul Goel is a frontend developer, loves to talk about modern Javascript, frontend architecture, opensource, promotes PWAs (#teamWeb) and is expert in developing browser extensions..
@trishulgoel