Capture key combo

Hello all,

Trying to catch when the user press “Alt + Shift + D”

https://codepen.io/Artrayd/pen/WVEzyz

function KeyPress(e) {
    
      var evtobj = window.event? event : e

      console.log (e.keyCode)

      if (evtobj.keyCode == 18 && evtobj.keyCode == 68 && evtobj.keyCode == 65) {
        alert("GG!");
      }
      e.preventDefault()
}

document.onkeydown = KeyPress;

But it doesn’t work(

Hi @ninjes , at the moment you are reacting to the keydown of both Alt (18) and d (68) buttons.
You are not checking for Shift (16).

Sorry, just tried for a moment without shift… Doesn’t work either.

after a bit of search I saw that it’s better to look only for D through the key codes. Alt and Shift are checked in another way.

if (evtobj.keyCode == 68 && eventobj.altKey && eventjob.shiftKey)...

https://www.w3schools.com/jsref/event_key_shiftkey.asp

Edit: on MDN it’s written that the attribute keyCode is deprecated and “key” should be used instead. While keyCode returned a Number, key returns a DOMString.

Seems like it should work, but still doesn’t work event with “key”(

  1. You have three different event objects and you are using a number instead of the string.
if (evtobj.key == 68 && eventobj.altKey && eventjob.shiftKey) {
  alert("GG!");
}

Should be:

if (evtobj.key === "D" && evtobj.shiftKey && evtobj.altKey) {
  alert("GG!");
}
  1. Your ternary is broken, it is missing the space.

var evtobj = window.event? event : e

Should be:

var evtobj = window.event ? event : e

https://codepen.io/anon/pen/QeMVpo

I think there’s something weird going on here because of the use of the Alt key. For example, changing it to the ctrl key here, works just fine for me:

function KeyPress(e) {
    
      var evtobj = window.event ? event : e

      console.log (e.keyCode)

      if (evtobj.shiftKey && evtobj.keyCode == 68 && evtobj.ctrlKey) {
        alert("GG!");
      }
      e.preventDefault()
}

document.onkeydown = KeyPress;

Maybe because Alt often changes focus from the web document to the browser navigation?

Very weird, nothing of this works in my browser. It detects well separate keys, but not combos. Alt shouldn’t change focus, tab changes it

  1. This might be a stupid question but are you giving the page focus (click the page) before pressing the buttons? Because it won’t work if the focus is in the code box.

  2. What browser are you running it in?

  1. Yes, of course…
  2. Chrome on MacOS

Does it work for you?

Yes, the Codepen I posted a link to works for me.

On MacOS Alt is the Cmd or Option key ?

Edit: Try checking the keys on this page
https://keycode.info

function keyevents(e){
        if (e.which === "17") {
                  alert('your has press Enter');
        }else{
                  alert(e.which);
        }
}
keyevents();