Language/JavaScript
[JS] Input keydown 이벤트가 두번 실행될 때
taedonn
2023. 10. 4. 13:35
728x90
오류 발생 조건
Keydown 이벤트를 실행할 때, 첫 keydown 이벤트가 두 번 실행되는 경우가 있다. 영어로 입력했을 때는 발생하지 않기 때문에 한글(?) 관련된 오류인 것 같은데, 이것저것 테스트해 봤더니, 크롬 브라우저에서 한글로 입력한 경우에만 오류가 발생했다.
isComposing 메서드
이벤트 중복 실행을 방지하기 위해 isComposing이라는 메서드를 사용했다. isComposing 메서드는 keydown과 keyup 이벤트 사이에 같은 이벤트가 중복 실행되는 걸 체크해 true/false를 반환하는 메서드다.
JavaScript 사용 예시
document.addEventListener("keydown", (e) => {
if (e.isComposing) return;
// 실행할 이벤트
.
.
.
});
React 사용 예시
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.isComposing) return;
// 실행할 이벤트
.
.
.
}
코드 적용 후
728x90