javascriptjquerypointerlock

Identify mouse events during requestPointerLock


Is there any way to identify right click event ("contextmenu") & scroll events while pointer lock API is enabled? I am trying to create a browser-based 3d game in which the player will be able to perform different activities by left clicking, right clicking, middle clicking and scrolling - while pointer is locked.

index.html

<body><button id="lock">Start game</button</body>

app.js

$("#lock").on("click", function(e) {
  lockPointer(); // invokes the requestPointerLock API
  e.stopPropagation();
});

// this works perfectly
$("body").on("click", function(e) {
  // do stuff on left click
});

// this does not work
$("body").on("contextmenu", function(e) {
  // do stuff on right click
});

Solution

  • For right click you can use mousedown or mouseup event, it works with requestPointerLock

    $('body').on('mousedown', function(e) {
        if (e.which === 1) {
            // left button
        } else if (e.which === 2) {
            // middle button
        } else if (e.which === 3) {
            // right button
        }
    });
    

    For scrolling you can use wheel event:

    $('body').on('wheel', function(e) {
        var dx = e.originalEvent.deltaX;
        var dy = e.originalEvent.deltaY;
    
        if (dy < 0) {
            // scroll up
        } else if (dy > 0) {
            // scroll down
        }
    
        if (dx < 0) {
            // scroll left (some mice support this)
        } else if (dx > 0) {
            // scroll right (some mice support this)
        }
    });