Search code examples
javascriptkeyboarddom-events

How can I detect if left Alt + letter was pressed


I need to perform some action only if the left ALT key was pressed with the letter s. I can find whether some Alt+s pressed using the keydown event, when oEvent.altKey === true and String.fromCharCode(oEvent.keyCode) === 'S'. I can also find whether the left or right ALT was pressed by:

oEvent.originalEvent.location === KeyboardEvent.DOM_KEY_LOCATION_LEFT 

or

oEvent.originalEvent.location === KeyboardEvent.DOM_KEY_LOCATION_RIGHT

But what I could not find is the way to combine the two.


Solution

  • For make this you have to register two events, keyUp and keyDown and using a single variable can do the trick,

     isleftAltPressed : false,
    
    keyUp: function(e)
    {
      var keyCode = e.which ? e.which : e.keyCode;
      if(keyCode == 18)
          isleftAltPressed = false;
    },
    
    keyDown: function(e)
    {
      var keyCode = e.which ? e.which : e.keyCode;
    
      if(keyCode == 18 && e.originalEvent.location === KeyboardEvent.DOM_KEY_LOCATION_LEFT)
          isleftAltPressed = true;
    
        if(e.altKey && isleftAltPressed && keyCode == 83)
          alert("hi");
    
    },