Can I find out if the file entry dialog closes?

I have an input file selector and I want to know when the modal closes if no file is selected. I only know the change, which only works when selecting a file or change

<input type="file" id="selector">
$("#selector").on("change", function() {
    //Changed
});
+4
source share
2 answers

try it

    <input type='file' id='testfile' style='display:none' />
    <button onclick='document.getElementById("testfile").click()'>Upload</button>

<script>
var testfile = document.getElementById('testfile')

testfile.onclick = focus();

function focus()
{
    document.body.onfocus = invoke();

}

function invoke()
{
    if(testfile.value.length)
    {
    alert('has file');
    }
    else {alert('empty')}
</script>
+2
source

When a dialog opens, it gains focus, so the browser window loses focus. Focus will be returned when the dialog is closed. You should subscribe to the focusevent on window, but since the window may lose and gain focus due to many reasons, you must save the flag if the dialog was opened.

The following code works in:

  • Chrome 63.0.3239.84 x64 on Windows 7
  • Internet Explorer 11.0.9600.18860 Windows 7
  • Opera 12.18 1872 x32 Windows 7

:

  • Firefox 58.0b11 (64- ) Windows 7

function now() {
  return window.performance ? performance.now() : +new Date
}

var isFileDialogOpened = false;

var input = document.querySelector('input');

input.addEventListener('click', function (e) {
  console.log('clicked', now())
  isFileDialogOpened = true
})

input.addEventListener('blur', function (e) {
  console.log('input blur', now())
  isFileDialogOpened = true
})

window.addEventListener('focus', function (e) {
  if (isFileDialogOpened) {
    console.log('closed (window got focus)', now())
    isFileDialogOpened = false
  }
})
<input type=file>
Hide result
0

Source: https://habr.com/ru/post/1691421/


All Articles