2

How can I trigger a select file dialog on iOS 6 for an input element in the DOM programatically? (i.e. using Javascript)

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

Notes:

  • Mobile Safari and Safari seems to behave differently. I've got it working using document.querySelector("input[type=file]").click() in safari.
  • If it's within a native clickhandler, i.e. initiated by the user, it seems to work, but I'd like to trigger the dialog on will.
sandstrom
  • 14,554
  • 7
  • 65
  • 62
  • Have you tried focus() ? – Simon Germain Oct 09 '12 at 18:23
  • How about `document.querySelector('#foo').click();` ? – Simon Germain Oct 09 '12 at 18:31
  • 1
    I don't believe you can. Just because it's a security risk with files. I've looked into this in the past, but it's really not encouraged for the developer to have control over this. On the other hand, there are several ways to "hide" the file element on top of another element, so that it seems like a user clicks on the other element, but is actually clicking on the file element - effectively triggering the dialog. – Ian Oct 09 '12 at 18:32
  • 1
    [This](http://stackoverflow.com/a/3030174/420001) answer seems to point towards no, although not Mobile Safari specific. – Josh Oct 09 '12 at 19:18

1 Answers1

4

After some more research it seems like this isn't possible. Least I haven't found a method that works.

I decided to solve this using an <input type='file'> positioned on top of the button, with opacity 0.01 to make the button visible.

sandstrom
  • 14,554
  • 7
  • 65
  • 62
  • 2
    Have you noticed an odd behavior, wherein *sometimes* Safari offers the user the choice of taking a picture or choosing an already-taken photo, but sometimes it does not? It's driving me crazy at the moment :-) – Pointy Oct 15 '12 at 14:23
  • DoH! I just figured it out :-) If you give the `` the "multiple" attribute, you just have access to the stored photos. Without "multiple" it offers the camera too. – Pointy Oct 15 '12 at 14:32