input 태그에 입력을 한 뒤에 따로 submit 버튼을 클릭하는 게 아니라 enter키로 이벤트를 실행하기 위해 아래와 같은 코드를 사용했었다.
<body>
<input type="text" id="inputBox" />
</body>
const inputBox = document.getElementById("inputBox");
inputBox.addEventListener("keydown", (e) => {
if (e.keyCode == 13) {
console.log("엔터 눌렀을 때만 실행");
}
});
키보드의 각 key마다 숫자로 된 keyCode가 있는데 엔터키의 경우 그게 13이라서 누른 키의 keyCode가 13이면 실행하도록 하는 코드이다.
키보드 이벤트의 종류에는 keypress, keydown, keyup이 있는데 차이점은 아래와 같다.
keypress: charater value을 생성하는 키(알파벳, 숫자, 구두점 등)가 눌렸을 때만 실행 (alt, shift, ctrl 등 제외) deprecated라 사용 권장하지 않음
keydown: 키를 눌렀을 때 실행
keyup: 키를 눌렀다가 땔 때 실행
위와 같이 작성하니 vscode가 가로줄을 긋길래 뭔지 보니까 deprecated 됐으니 더이상 추천하지 않는단다...
그럼 이제 어떻게 해야하나 찾아보니 keycode 대신에 key나 code를 사용하란다.
콘솔로 엔터에 해당하는 KeyboardEvent를 뽑아보니
엔터는
넘패드 엔터는
서로 key는 동일하지만 code는 구별되어있는 걸 확인할 수 있었고, 엔터든 넘패드 엔터든 구별하지 않기 위해 key를 사용했다.
방법 1.
const inputBox = document.getElementById("inputBox");
inputBox.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
console.log("엔터 눌렀을 때만 실행");
}
});
방법 2.
const inputBox = document.getElementById("inputBox");
inputBox.addEventListener("keydown", enter);
function enter(e) {
if (e.key === "Enter") {
console.log("엔터 눌렀을 때만 실행");
}
}
방법 3.
const inputBox = document.getElementById("inputBox");
inputBox.onkeydown = enter;
function enter(e) {
if (e.key === "Enter") {
console.log("엔터 눌렀을 때만 실행");
}
}
[JavaScript] 객체 비구조화(구조 분해) (0) | 2021.08.16 |
---|---|
[JavaScript] 함수의 매개변수에 들어올 기본값 설정하기 (0) | 2021.08.15 |
[JavaScript] script 태그의 위치와 async, defer (0) | 2021.05.27 |
[JavaScript] Uncaught TypeError: Cannot read property 'addEventListener' of null (0) | 2021.05.24 |
[JavaScript] Spread Operator 펼침연산자 (0) | 2021.05.01 |