execute function when closing (cancel) the window that opens input file

0

I have a common input file. Pressing opens the corresponding window to choose a file from your computer.

I have a function that loads a gif of "loading" when you click on the input button; and when selecting the image and processing the sending of the image by ajax to the server this gif is hidden.

But how do I hide the gif if the user gives "cancel" or closes the window without choosing a file?

The gif is hidden when selecting and processing an input file because the onchange event is launched.

How can I do it?

<input type="file" id="file"/>

JS:

 $("#file").on("click", function(){
  $(".gif").show();

});
$("#file").on("change", function(){

$.ajax({
    ...,
complete(){
    $(".gif").hide();
    }
});

});
    
asked by user2930137 21.07.2017 в 00:26
source

3 answers

0

This is the most successful thing I have come to implement, since the browser does not tell JS when the user closes the window (by whatever method) and it does not select a file to upload. jsfiddle.net/Shiboe/yuK3r/6

    
answered by 21.07.2017 / 23:12
source
0

I can think of 2 ways to do it:

1. You can add an event to the close button of the modal window so that you hide your gif ( The best option ).

2. Create a function that asks every X time if the modal is visible. If it is not, then hide the gif:

$("#file").on("change", function(){

 var id = setInterval(function(){

         if(!$("#id-modal").is(":visible")) {
           $(".gif").hide();
           clearInterval(id);
        }
 });

//..

});
    
answered by 21.07.2017 в 03:45
0

The error in your code is that you show the gif independent if the action is performed or not, without mentioning that the gif is only shown if the user clicks the input, it would fail to show if the user uses the 'tab' key to access the input.

The solution is simple

$("#file").on("change", function(){
$(".gif").show()
$.ajax({
    ...,
complete(){
    $(".gif").hide();
    }
});

});

The interesting thing about onchange is that it is only called when the value of the input changes, if the user gives cancel then the value remains intact, and the event onchange is not executed.

    
answered by 21.07.2017 в 04:15