개발하다가 글쓰는 블로그

웹페이지에서 단축키 사용하기 본문

개발

웹페이지에서 단축키 사용하기

지존개발자킹 2022. 10. 22. 18:11

웹페이지에서 js로 단축키 처럼 사용할 수 있도록 기능을 추가 하기 위해서 관련 코드를 찾아봤다.

 

많은 곳에서

document.onkeyup = function(e) {
	if (e.which === {{key code}}) {
		// 로직
	}
}

위와 같은 형식으로 입력 키를 감지하는 코드를 예시로 작성해 놓은 것을 볼 수 있었다.

 

하지만

UIEvent.which는 deprecated 되었기 때문에 기존 작성된 코드가 아니라면 사용하지 않는게 좋겠다.

MDN에서는 대안으로 keyCode 또는 charCode 를 사용하라고 제시하고 있는데

charCode, keyCode 또한 deprecated 되었다.

 

code를 쓰는 방법과 key를 쓰는 방법이 있지만 

code의 경우에는 qwerty기준으로 코드를 반환하므로 dvorak 등 다른 키배열을 사용하는 경우 문제가 될 수 있다.

(그럴 일은 잘 없겠지만)

 

그래서 key를 쓰는게 가장 무난한 방법이라고 할 수 있겠다.

키 값이 그대로 반환되므로 키 코드를 사용할 필요도 없다! (아래 예시 참고)

document.onkeyup = function(e) {
	if (e.key === "F10") {
		// F10 눌린 경우
        } else if (e.key === "a") {
    		// a 눌린 경우
        }
}

 

https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/which

 

UIEvent.which - Web APIs | MDN

The UIEvent.which read-only property of the UIEvent interface returns a number that indicates which button was pressed on the mouse, or the numeric keyCode or the character code (charCode) of the key pressed on the keyboard.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent

 

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