본문 바로가기
프론트엔드/JavaScript

[자바스크립트] 키보드 이벤트 (keyboard event) 종류

by CODESIGN 2022. 4. 15.

키보드 이벤트 (Keyboard Event)

사용자가 키를 누르거나 키를 놓을 때 발생하는 이벤트입니다. 

 

키보트 이벤트의 종류

 keydown 

  • 사용자가 키보드의 키를 눌렀을 때 발생합니다.

 keyup 

  • 사용자가 키보드의 키를 눌렀다가 떼었을 때 발생합니다. 

 keypress 

  • 사용자가 키보드의 키를 눌렀을 때 발생합니다.
  • Alt, Ctrl, Shift, Esc 등 몇 가지 키에서는 이 이벤트를 발생시키지 않습니다.
  • 현재는 deprecated 되어 사용을 권장하지 않습니다.

 

keydown, keyup, keypress 사용 예제

input에 keydown, keyup, keypress 이벤트를 등록해줌으로써

키보드의 키가 눌려 이벤트가 발생하면 그에 맞게 이벤트 이름을 출력합니다.

 

입력창에 하나의 키를 오래 누르고 있으면

keydown, keypress, keydown, keypress... 가 반복적으로 발생하며 그 결과를 출력하고,

마지막에 키보드 키에서 손을 떼었을 때, 

keyup 이벤트가 발생하여 keyup을 출력합니다.

 

 

 

 

 

 

 

Reference

 

KeyboardEvent - Web APIs | MDN

KeyboardEvent objects describe a user interaction with the keyboard; each event describes a single interaction between the user and a key (or combination of a key with modifier keys) on the keyboard. The event type (keydown, keypress, or keyup) identifies

developer.mozilla.org

 

댓글