본문 바로가기
웹/HTML, CSS, Javascript

[Event] Ctrl, Alt, Shift키 눌림 여부 반환 (feat. getModifierState 함수 없음 오류)

by 유.독 2023. 8. 29.
반응형

안녕하세요 유.독입니다!

javascript 작업 중, 그냥 클릭했을 때와 Ctrl키를 누르고 클릭했을 때에 동작방식을 다르게 하고 싶어서 찾아본 내용을 정리해보았습니다. 간단하니 바로 예시를 보여드리며 설명하겠습니다.

 

예시

<html>
    <head></head>
    <body onclick="bodyClickFunc(event)"></body>
</html>

<script>
    function bodyClickFunc(event) {
      if (event.ctrlKey) {
        alert("ctrl 입력");
      } else {
        alert("ctrl 비입력");
      }
    }
</script>

이벤트 함수에서는  event 객체를 받을 수 있는데요,  ctrl키 입력여부를 확인하기 위해서 ctrlKey 속성값이 true인지 false인지 확인하면 됩니다.


키 관련 event 속성

자주 사용하는 키

event.ctrlKey //ctrl
event.altKey //alt
event.shiftKey //shift

 

기타 키 눌림여부 확인

event.getModifierState("CapsLock") //"Alt", "ScrollLock" 등등 가능

Ctrl, Alt, Shift 키를 Modifier keys라고 부른다는데요,

이 함수를이용하면 CapsLock 키 또는  눌렸는지 확인할 수 있습니다. 

 

키 리스트

https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values#modifier_keys

 

Key values for keyboard events - Web APIs | MDN

The tables below list the standard values for the KeyboardEvent.key property, with an explanation of what the key is typically used for. Corresponding virtual keycodes for common platforms are included where available.

developer.mozilla.org

MDN사이트에서 직접 확인해보세요!

 

getModifierState, undefined에러가 발생합니다!😥

태그에 직접 이벤트를 걸어준 경우 (정상)

<html>
    <head></head>
    <body onclick="bodyClickFunc(event)"></body>
</html>

<script>
    function bodyClickFunc(event) {
      if (event.getModifierState("CapsLock")) { //"Alt", "ScrollLock" 등등 응용 가능
        alert("CapsLock 활성");
      } else {
        alert("CapsLock 비활성");
      }
    }
</script>

Jquery를 이용하여 이벤트를 걸어준 경우 (에러)

<html>
    <head>
    	<script src="[jquery cdn 경로]"></script>
    </head>
    <body id="body"></body>
</html>

<script>
    $("body").on('click', function (event) {
      event.getModifierState("CapsLock"); //getModifierState 함수가 없다는 에러 발생
    });
</script>

jquery로 이벤트를 걸어주었더니, crtlKey, altKey, shiftKey 속성은 지원하지만 getModifierState()함수는 지원해주지 않았습니다.


⏰마무리하며

왜 jquery에서는 getModifierState()함수가 미지원인지 모르겠지만, 여기서 급 마무리해보겠습니다!


Reference

getModifierState함수 관련 링크

https://www.w3schools.com/jsref/event_mouse_getmodifierstate.asp

 

MouseEvent getModifierState() Method

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

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

 

MouseEvent: getModifierState() method - Web APIs | MDN

The MouseEvent.getModifierState() method returns the current state of the specified modifier key: true if the modifier is active (i.e., the modifier key is pressed or locked), otherwise, false.

developer.mozilla.org

 

참조 블로그

 

https://homzzang.com/b/js-1406

 

홈짱닷컴

홈페이지 제작, 그누보드 강의, 웹코딩, HTML, CSS, JAVASCRIPT, JQUERY, PHP, SQL

homzzang.com

 

반응형