2

I have a input field with the type=file to select an image file but what I want is that if someone opens the file selector dialog and on some particular event it automatically / programmatically closes the dialog without hitting the cancel button by the user. Is there any way to do it with js/jquery?

Tommy
  • 2,355
  • 1
  • 19
  • 48
Hamza
  • 23
  • 1
  • 5
  • I'm fairly certain there is no way to close the open file dialog like that. What are you trying to achieve that would require closing it programmatically? – Herohtar Nov 02 '18 at 20:37
  • As far as I'm aware: no, it's not possible for a website's javascript code to control system dialogs that deal with the machine's file system due to the potential security risks that would involve. – rickdenhaan Nov 02 '18 at 20:37
  • The image field is build with a drag&drop library so if user opens the file dialog and drag/drop the image(from the dialog) instead of selecting it then the image gets upload but the dialog box remains open and it has to close by clicking the close button. I just want to make it close if by any means the file is uploaded – Hamza Nov 02 '18 at 20:50
  • Yeah, i was the same feeling but it's happening when user drag the image and drop it to the input field region – Hamza Nov 02 '18 at 21:07
  • Hm, it seems that some browsers let you drag files in even when the dialog is open, but some don't. Chrome will, but not Edge. Maybe another option would be to try blocking drag/drop while the dialog is open since it's not possible to close it from JavaScript. – Herohtar Nov 02 '18 at 21:09

2 Answers2

3

Interaction with <input type="file" /> is very limited. There is no way to close the file dialog programmatically. You could potentially try to disable the drag/drop functionality while the dialog is open by handling the click event; however, it seems that there is no reliable cross-browser method for determining that the dialog has been closed in a case where the user clicks cancel, so re-enabling it may be tricky.

Unfortunately, you will likely just have to let the user close the file dialog on their own if they choose to drag/drop files from it instead of using the "open" button.

Herohtar
  • 5,347
  • 4
  • 31
  • 41
0

I think the answer to this is no. A file input change event opens a native browser window, this cannot be controlled using Javascript.