0

I am new to JavaScript and learning event handlers. How to detect click + specific key pressed concurrently? For example click+D, using pure (vanilla) js.

Edit:
I tried this way but its not detecting the click event when key is pressed. The console.log("key "+keyPressed) statement is also executed continuously while key is in pressed state.

keyPressed=false;

function keyDown(event) {
    var x = event.key;
  
    if (x == "a" || x == "A") { 
         keyPressed=true;
         console.log("key "+keyPressed);
    }

  }

function keyUp(event){

  keyPressed=false;
  
  console.log("key "+keyPressed);

}

 function clickHelper(event){
  console.log("---");
    if(keyPressed){
      console.log("*****");
    }
 } 
No Name
  • 51
  • 1
  • 6
  • You need to track keypresses first and match your condition on click, many examples here: https://stackoverflow.com/questions/1828613/check-if-a-key-is-down – savageGoat Oct 05 '22 at 17:42

1 Answers1

1

IIRC you cannot use one event to detect if the mouse is held down AND a button is clicked. However, you can set a property called mouseDown of the document and register an event listener for mouse state.

var mouseDown = 0;
document.body.onmousedown = function () {
    ++mouseDown;
};
document.body.onmouseup = function () {
    --mouseDown;
};

document.body.onkeydown = function (e) {
    if (mouseDown && e.key === 'd') {
        alert('D was pressed while clicking');
    }
};

I used some code from this stackoverflow post for this.

Ethan R
  • 338
  • 2
  • 9