$("#selector").on("change", function()" />

Is possible to know when file input dialog is closing?

javascript jquery

202 观看


22 作者的声誉

I have a input file selector and I want to know when the modal is closing if a file is not selected. I only know the change which only works when a file is selected or changes

<input type="file" id="selector">
$("#selector").on("change", function() {
作者: Charlie Chandelier 的来源 发布者: 2017 年 12 月 27 日

回应 (2)


173 作者的声誉

Try this

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

var testfile = document.getElementById('testfile')

testfile.onclick = focus();

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


function invoke()
    alert('has file');
    else {alert('empty')}
作者: Habib Ur Rehman 发布者: 27.12.2017 05:16


8379 作者的声誉

When the dialog is opened, it gets focus, so the browser window loses focus. The focus will be back when the dialog is closed. You have to subscribe focus event on window, but as window can lose and get focus because of a lot of reasons, you have to keep a flag if the dialog have been opened.

Following code works in:

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

and does NOT work in:

  • Firefox 58.0b11 (64-bit) on 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>

作者: Qwertiy 发布者: 27.12.2017 05:53