JSFiddle - React, Tailwind, and code Playground
by ajai jothi
HTML
<input type="text" autofocus>
JavaScript 1.7
const isIos = () => !!window.navigator.userAgent.match(/iPad|iPhone/i);
const hasInteracted = (() => {
let interacted = false;
const onTouchStart = () => {
interacted = true;
document.removeEventListener(onTouchStart);
};
document.addEventListener('touchstart', onTouchStart);
return () => interacted
})();
const FOCUS_TYPES = {
REAL: 'real',
FAKE: 'fake'
};
const getFocusType = () => (hasInteracted() || !isIos()) ?
FOCUS_TYPES.REAL :
FOCUS_TYPES.FAKE;
const focus = (input) => {
input.classList.add('has-focus')
const onBlur = (input) => {
input.classList.remove('has-focus')
document.removeEventListener(onBlur)
}
input.addEventListener('blur', onBlur)
input.scrollIntoView()
};
document.addEventListener('DOMContentLoaded', () => {
const autofocusedInput = Array.prototype.slice.call(
document.querySelectorAll('input')
).filter((el) => el.hasAttribute('autofocus'))[0]
focus(autofocusedInput)
});