Skip to content

Instantly share code, notes, and snippets.

@azaek
Last active March 29, 2024 12:27
Show Gist options
  • Save azaek/a52ffe350ff408f5932ffb228f0ca4e4 to your computer and use it in GitHub Desktop.
Save azaek/a52ffe350ff408f5932ffb228f0ca4e4 to your computer and use it in GitHub Desktop.
Trigger focus with soft keyboard dynamically on safari(ios)
import { RefObject } from "react";
/**
* This function helps to focus on an input element with soft keyboard on safari(ios).
* @notice This is a workaround for the issue where the soft keyboard does not show up on safari(ios) when focusing on an input element. Safari(ios) allows keyboard for subsequent focus on an input element if the focus is triggered by a user event like click or touchstart.
* @param target - RefObject of the input element to focus
* @param delay (optional) - delay in milliseconds before focusing on the input element can be 0 for instant focus
*/
export const focusInput = (target: RefObject<HTMLInputElement>, delay: number = 500) => {
// create invisible dummy input to receive the focus first
const fakeInput = document.createElement('input')
fakeInput.setAttribute('type', 'text')
fakeInput.setAttribute('aria-hidden', 'true')
fakeInput.setAttribute('readonly', 'true')
fakeInput.style.position = 'absolute'
fakeInput.style.opacity = "0"
fakeInput.style.height = "0"
fakeInput.style.fontSize = '16px' // disable auto zoom
// you may need to append to another element depending on the browser's auto
// zoom/scroll behavior
document.body.prepend(fakeInput)
// focus so that subsequent async focus will work
fakeInput.focus()
setTimeout(() => {
// now we can focus on the target input
target?.current?.focus()
// cleanup
fakeInput.remove()
}, delay)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment