I have a common input file. That when you press it opens the corresponding window to choose a file from your computer.
I have a function that loads me a "loading" gif when you click 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 hits "cancel" or closes the window without choosing a file?
The gif hides it when selecting and processing an input file because the onchange event is fired.
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();
}
});
});
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 can hide your gif ( The best option ).
2. Create a function that asks every X time if the modal is visible. If it isn't then you hide the gif:
This is a way that worked for me; it is one of the options that @Einer mentions only that the window that generates the input is taken
file
https://jsfiddle.net/cromerog/1b3seqrw/7/
What is done is that it is verified if the window has the focus; if it loses focus (cancels, presses
ESC
or selects a file) it sends to hide thegif
.It
<span id="status">
will simulate how thegif
.Taken as an example from:
https://forum.imasters.com.br/topic/556543-evento-ao-cancelar-input-file-com-jquery/?do=findComment&comment=2220313
The error in your code is that you
gif
display regardless of whether the action is performed or not, not to mention that the gif is only displayed if the user clicks the input, it would fail to display if the user uses the `tab' key to access it. to input.The solution is simple
The interesting thing about
onchange
it is that it is only called when the value of the input changes, if the user hits cancel then the value remains intact, and the event is not executedonchange
.This is the best I've ever implemented, since the browser doesn't tell JS when the user closes the window (by whatever method) and the user doesn't select a file to upload:
Here the example