Trip to Front-end
[JS] 우클릭 인식은 어떻게 구현하는 것일까?
Kestrel
2023. 3. 23. 09:26
코드 챌린지를 하다가 이벤트리스너를 복습하고 있었는데 역시 하다보면 구멍이 슝슝 뚫려있는 곳이 많았다.
그 중 하나가 우클릭을 어떻게 구현하는 것인가였다. 구글링하면 금방 나올줄 알았는데 안나오고 다들 클릭 이벤트 종류에 대해서만 다뤄서 이 글을 남긴다. 역시 검색은 영어로 찾아야한다;
const superEventHandler = {
mouseOver: function () {
hello.innerText = "The mouse is here!";
hello.style.color = colors[0];
},
mouseOut: function () {
hello.innerText = "The mouse is gone!";
hello.style.color = colors[1];
},
reSized: function () {
hello.innerText = "You just resized!";
hello.style.color = colors[2];
},
rightClicked: function (e) {
if (e.button === 2) {
hello.innerText = "That was a right click!";
hello.style.color = colors[3];
}
}
};
hello.addEventListener("mouseover", superEventHandler.mouseOver);
hello.addEventListener("mouseout", superEventHandler.mouseOut);
window.addEventListener("resize", superEventHandler.reSized);
window.addEventListener("mousedown", superEventHandler.rightClicked);
이런건 event를 보면서하라고 배웠는데 내용이 많다보니 나같은 초보자는 뭘 써야할지 모른다. 그래서 찾다보니 버튼에 번호가 부여되어 있다는 것을 알게 되었다.
0: 좌클릭, 1: 휠버튼, 2: 우클릭, 3, 4: 요즘 마우스 거의 있는 좌측에 붙어 있는 버튼 두개
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
MouseEvent.button - Web APIs | MDN
The MouseEvent.button read-only property indicates which button was pressed on the mouse to trigger the event.
developer.mozilla.org