Search code examples
javascriptkeyboard-events

How to detect in Javascript when the ALT key is pressed?


We are creating a web user interface that looks like a desktop window. Now we need to handle the Alt key. When Alt key is pressed the focus goes to the upper menu.

In Javascript, how to get the event for Alt key when ONLY Alt key is pressed?

I need to ensure that no other key was pressed at the same time.


Solution

  • I don't know if this is the most elegant solution, but it worked fine.

    $(function()
    {
        //Flag to check if another key was pressed with alt
        var vAnotherKeyWasPressed = false;
        //ALT keycode const
        var ALT_CODE = 18;
    
        //When some key is pressed
        $(window).keydown(function(event)
        {
            //Identifies the key
            var vKey = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
            //The last key pressed is alt or not? 
            vAnotherKeyWasPressed = vKey != ALT_CODE;
        });
    
        //When some key is left
        $(window).keyup(function(event)
        {
            //Identifies the key
            var vKey = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    
            //If the key left is ALT and no other key is pressed at the same time...
            if (!vAnotherKeyWasPressed && vKey == ALT_CODE)
            {
                //Focus the menu
                $('#myMenu').focus();
                //Stop the events for the key to avoid windows set the focus to the browser toolbar 
                return false;
            }
        });
    });