Search code examples
htmlhtml5-canvasonkeydown

html5 onkeydown, check if a form element is selected


I'm working on an html5 canvas game and am using document.onkeydown to test input. However, I want to add a check in the onkeydown to make sure no form elements are selected, particularly the chat box. How do I check for that?

Here's my code for onkeydown

document.onkeydown = function(event) {
                var keyCode;

                if(event == null)
                {
                    keyCode = window.event.keyCode;
                }
                else
                {
                    keyCode = event.keyCode;
                }
                var message = {
                    'msgId': 4
                };

                switch(keyCode)
                {
                    // left
                    case 65:
                        message['move'] = 0;
                        connection.send(JSON.stringify(message));
                        break;

                    // up
                    case 87:
                        message['move'] = 1;
                        connection.send(JSON.stringify(message));
                        break;

                    // right
                    case 68:
                        message['move'] = 2;
                        connection.send(JSON.stringify(message));
                        break;

                    // down
                    case 83:
                        message['move'] = 3;
                        connection.send(JSON.stringify(message));
                        break;

                    default:
                    break;
                }
            }

Solution

  • Normally an html Canvas does not receive it's own keyboard events.

    But if you give a canvas a tabindex, it then does receive its own keyboard events.

        // set canvas to be a tab stop (necessary to get keydown events)
    
        myCanvas.setAttribute('tabindex','0');
    

    Then you can listen for key events specifically on your canvas rather than the window.

        // have handleKeydown handle keydown events on the canvas
    
        myCanvas.addEventListener('keydown',handleKeydown,false);
    

    As with all text input elements, the use must click on the canvas to give it focus.

    But, you can force the canvas to have focus

        // set focus to the canvas so keystrokes are immediately handled
    
        canvas.focus();
    

    [ Addition -- determining if the key event was raised in an input element ]

    If you want determine which element raised the key event, you could examine the event.target.tagName property of the event that was raised.

    document.onkeydown = function(event) {
    
        // if the key occurred in an input element...just exit 
    
        if(event.target.tagName=="INPUT"){ return; }
    
        // the keystroke wasn't in an input element, do your stuff!
    
        ...