Reputation: 63
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() {
//Changed
});
Upvotes: 6
Views: 4941
Reputation: 21400
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:
and does NOT work in:
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>
Upvotes: 3
Reputation: 198
Try this
<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>
Upvotes: 2