javascriptdom-events

Is there an alternative to deprecated e.which in JavaScript?


Im new to JavaScript event handling, I would like to trigger an event upon mousemove and left-click on a div element. My current implementation is to check that e.which == 1 when I trigger the mousemove event function. However, I have read that the e.which property is now deprecated (https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which). My code:

div.addEventListener("mousemove", myEventFunction)

function myEventFunction(e){
    if (e.which == 1){
       //do something
    }

}

Is there any alternative to perform this operation?


Solution

  • You can use event.button if it is gonna be a mouse event.

    The MouseEvent.button read-only property indicates which button was pressed on the mouse to trigger the event.

    function myEventFunction(e) {
        e = e || window.event;
        if ("buttons" in e) {
            return button;
        }
        var button = e.which || e.button;
        return button;
    }
    

    The above function returns the button value.