본문 바로가기
✘✘✘ Javascript

[javascript][event] Detect mouse right click: context menu

by PrettyLog 2022. 7. 5.

Is right click a Javascript event?

Search: how to detect mouse right click in javascript

window.oncontextmenu = function () {
  alert('Right Click')
}
$("#myId").mousedown(function(ev){
      if(ev.which == 3)
      {
            alert("Right mouse button clicked on element with id myId");
      }
});

javascript detect right click Code Example

document.body.onclick = function (e) {
    var isRightMB;
    e = e || window.event;

    if ("which" in e)  // Gecko (Firefox), WebKit (Safari/Chrome) & Opera
        isRightMB = e.which == 3; 
    else if ("button" in e)  // IE, Opera 
        isRightMB = e.button == 2; 

    alert("Right mouse button " + (isRightMB ? "" : " was not") + "clicked!");
}

MouseEvent.button

A number representing a given button:

  • 0: Main button pressed, usually the left button or the un-initialized state
  • 1: Auxiliary button pressed, usually the wheel button or the middle button (if present)
  • 2: Secondary button pressed, usually the right button
  • 3: Fourth button, typically the Browser Back button
  • 4: Fifth button, typically the Browser Forward button

HTML

<button id="button" oncontextmenu="event.preventDefault();">
    Click here with your mouse...
</button>
<p id="log"></p>Copy to Clipboard

JavaScript

let button = document.querySelector('#button');
let log = document.querySelector('#log');
button.addEventListener('mouseup', logMouseButton);

function logMouseButton(e) {
  if (typeof e === 'object') {
    switch (e.button) {
      case 0:
        log.textContent = 'Left button clicked.';
        break;
      case 1:
        log.textContent = 'Middle button clicked.';
        break;
      case 2:
        log.textContent = 'Right button clicked.';
        break;
      default:
        log.textContent = `Unknown button code: ${e.button}`;
    }
  }
}

댓글