-1

So on my website, I want to make a little box that shows the current mouse position only when I hold Alt+Z and disappear when I release the hotkey.

Karim AlAhmed
  • 23
  • 1
  • 5
  • 2
    Does this answer your question? [Detecting combination keypresses (Control, Alt, Shift)?](https://stackoverflow.com/questions/37557990/detecting-combination-keypresses-control-alt-shift) – avisionx Nov 17 '20 at 15:46
  • I think the main problem is the showing of a box that is at the current mouse position, and combining that with the event listeners – Samathingamajig Nov 17 '20 at 15:49

3 Answers3

0

You can do that by adding the next method to the document.onkeyup event:

document.onkeyup = function(e) {
  if (e.altKey && event.key == "z") {
    alert("ALT + Z keys were pressed");
  }
};
QuazBuzz
  • 1,112
  • 1
  • 8
  • 18
0

You can listen for a shortcut (an event) using the addEventListener method:

document.addEventListener('keyup', function (event) {
    if (event.key == "z" && event.altKey){
        console.log("Alt + Z pressed!")
        // Do some other stuff here
    }
})

This applies to the entire document; If you want to only add the listener for a certain element, this method would exist for that HTMLElement too.

Here's a live jsfiddle demo.

Vthechamp
  • 636
  • 1
  • 8
  • 20
0

This should solve your problem.

window.addEventListener("keydown", e => {
    if(e.keyCode == 90 && e.altKey) alert("Hello World!");
});
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
Joseph
  • 11
  • 2