.focus()를 사용하면 타깃 input에 focus 이벤트를 강제로 트리거 할 수 있습니다.
<input type="text" name="my-input" />
const input = document.querySelector('[name=my-input]')
(input as HTMLInputElement).focus();
위 코드는 데스크톱과 모바일 둘 다 문제없이 동작하지만, 모바일에선 focus() 함수가 실행된 후 키보드가 자동으로 띄워지지 않습니다. 이는 모바일 브라우저 설계자가 의도적으로 만든 프로세스로써, 사용자가 의도하지 않은 액션을 차단해서 UX를 개선한 것이죠. 그래서 원칙적으로는 사용자가 input을 탭 해야지만 키보드가 올라옵니다.
하지만 사용자의 편의성을 고려해 강제로 키보드를 띄워주고 싶은 경우엔 아래와 같은 트릭들을 사용할 수 있습니다.
트릭 1
new Promise((resolve) => {
resolve(null);
}).then(() => {
const input = document.querySelector('[name=my-input]')
(input as HTMLInputElement).focus();
});
트릭 2
const input = document.querySelector('[name=my-input]')
(input as HTMLInputElement).focus();
(input as HTMLInputElement).setSelectionRange(0, 0);
키보드가 잘 띄워지지만, 무슨 이유때문인지 비동기 코드에선 동작하지 않습니다.
예를 들어, 아래와 같은 상황에서 말이죠.
await const res = axios.get('/api/email'); // 추가
new Promise((resolve) => {
resolve(null);
}).then(() => {
const input = document.querySelector('[name=my-input]')
(input as HTMLInputElement).focus();
});
비동기 코드가 후행되면, 이전 코드는 동기적 코드이기 때문에 동작합니다.
'JavaScript' 카테고리의 다른 글
WebRTC로 1:1 영상 통화 구현 (0) | 2024.04.07 |
---|