Capturing the close of the browse for file window with JavaScript

setlio picture setlio · Aug 22, 2012 · Viewed 14.4k times · Source

I am using infile to ask the users to browse for a file on their machine. Is there way to catch if the window is closed without file being selected?
For example if x is clicked.

<input type="file" name="data" id="inFile" size="15" style="display:none" onchange="handleFiles(this)"/>

Thanks

Answer

Bergi picture Bergi · Aug 26, 2012

With the solution from HTML input file selection event not firing upon selecting the same file, I think you can use this:

<input type="file" name="data" id="inFile" />
var fileElem = document.getElementById("inFile");
var fileSelected = null;
fileElem.onclick = function(e) {
    fileSelected = this.value;
    this.value = null;
});
/* or use this in your browse() function:
    fileElem.value = null;
*/
fileElem.onchange = function(e) { // will trigger each time
    handleFileDialog(this.value === fileSelected);
};

function handleFileDialog(changed) {
    // boolean parameter if the value has changed (new select) or not (canceled)
}