Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 618
DavNej Avatar asked Oct 17 '22 20:10

DavNej


1 Answers

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.

like image 124
Praveen Kumar Purushothaman Avatar answered Oct 20 '22 10:10

Praveen Kumar Purushothaman