Left vs Middle vs Right Mouse Button

JavaScript FAQ | Keyboard & Mouse Events FAQ  

Question: How do I check whether the user clicked the left or right mouse button? Can I use an onclick event handler?

Answer: The click event is fired for the left mouse button; however, depending on the browser, click may or may not occur for the right button. (Notably, in Microsoft Internet Explorer the click event is not fired for the right button.) Therefore, we cannot reliably use onclick event handlers to perform the left-vs-right button test in a cross-browser fashion. Instead, to distinguish between the mouse buttons we can use mousedown events; most browsers do fire mousedown and mouseup events for any mouse button. In the following example, we'll use the mousedown event properties:

  • event.which in Firefox and Netscape Navigator (1 is left, 2 is middle, 3 is right)
  • event.button in Microsoft Internet Explorer (1 is left, 4 is middle, 2 is right)
  • event.button in Firefox and other W3C browsers (0 is left, 1 is middle, 2 is right)

    In this example the onmousedown event handler displays the messages LEFT button, MIDDLE button or RIGHT button, depending on the actual mouse button you have clicked. (Keep in mind that, for many mouse models, the scrolling wheel may play the role of the middle button!) Click or right-click anywhere on this page to see it work.

    var sTestEventType='mousedown';
    function handleMouseEvent(e) {
     var evt = (e==null ? event:e);
     var clickType = 'LEFT';
     if (evt.type!=sTestEventType) return true;
     if (evt.which) { 
      if (evt.which==3) clickType='RIGHT';
      if (evt.which==2) clickType='MIDDLE';
     else if (evt.button) {
      if (evt.button==2) clickType='RIGHT';
      if (evt.button==4) clickType='MIDDLE';
     alert(evt.type+': '+clickType+' button!');
     return true;
    document.onmousedown = handleMouseEvent;
    document.onmouseup   = handleMouseEvent;
    document.onclick     = handleMouseEvent;

    Note: Internet Explorer 8.x may fire click events for the middle button and set event.button=0, even though the middle and right buttons are normally associated with nonzero event.button values! This is one more reason not to use onclick event handlers for the left-vs-right button test in your cross-browser scripts.

  • [Test this event type: mousedown|mouseup|click  Now testing: mousedown ]
    For the purposes of this test, context menu is now disabled. Enable | disable the context menu.

    Copyright © 1999-2011, JavaScripter.net.