'Position of image <input> open dialog on Safari iOS
I need to trigger browser image selection from photo library/camera in response to user clicking a custom element (hiding the default <input>
).
Using the standard code often suggested for this.
The HTML:
<input id="image-input" style="display: none" type="file" accept="image/*"/>
<button onclick="browse()">BROWSE</button>
And script:
<script>
function browse() {
document.getElementById("image-input").click();
}
</script>
This works as expected but on iOS (iPhone, 15.4), the position of the popup dialog is unpredictable.
Most of the time the dialog pops up under the button but not exactly at the same place, and sometimes it just pops up at the bottom of the page. I can't seem to determine what user action causes the different behaviors.
If I remember correctly, in previous iOS versions this dialog would open as a fixed drawer at the bottom of the screen?
Is there any way to control the position of this dialog? Ideally, I'd like it to just open as a fixed modal drawer at the bottom but anything that can make a consistent controllable behavior would work too.
Solution 1:[1]
So I took a look at this issue on my iPhone 8+, Safari, iOS 15.2.1
I created this fiddle here to play around with:
https://codepen.io/treckstar_/pen/oNELeqY
I couldn't replicate the exact issue you are saying. What I got was the opposite. I unhid the file input so I could try clicking both of them and see what happens. Every few times I would click the "should be hidden" input, the file open dialog would open at the top where the browse button is.
Since we don't have the exact code, I can't be positive, but I am thinking that whatever hidden input you have is located somewhere at the bottom of the page and its just showing up where the last input was clicked was at.
I think the main issue is using JavaScript/jQuery to click a button causes intermittent positioning of the dialog box for file inputs on iOS Safari.
So I would recommend my solution to be, not use JavaScript/jQuery to click the file button.
You could potentially setup a button with the file upload positions over top of it, and with opacity set to 0.
#image-input {
position: absolute !important;
left: 0px;
top: 0px;
clip: rect(0px, 40px, 40px, 0px);
opacity: 0.0;
padding: 10px 0px;
}
<a id="image-file-button" data-role="button">Button</a>
<input id="image-input" type="file" data-role="none" name="image-file-upload" />
Solution 2:[2]
The cause of the popup moving could be that another element on the page is moving it and changing where it moves to, on different devices it will be in different places because it is moved to where it won't look smashed.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | treckstar |
Solution 2 | Cody B. |