setlio setlio - 2 months ago 10
Javascript Question

Capturing the close of the browse for file window with JavaScript

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

What I did is: Start timer after the user opens the window, and in that timed function I check every 0.5 sec if the file has been selected with boolean var. I stop the timer as soon as user selects the file or HTML5 DnD occurs. I hope this helps someone.

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

<button dojoType="dijit.form.Button" id="fileSelect" type="button" onmouseup="browse();">Browse</button> 

var fileselected = false;
function handleFiles(input){
    fileselected = true;
//use input
}

var interval;
function browse(){
    fileselected = false;
    var fileElem = document.getElementById("inFile");
    fileElem.click();
    interval = setInterval(setdiv, 500);

}
function setdiv(){
    if(!fileselected){  
        //do staff until user decides to Dnd or  browse for file again
        clearInterval(interval);
    }   
}