javascripttypescriptkeyboard

Typescript keyboard listener prevents typing into HTML input forms


I'm developing a web application with Angular2, with one component needing to listen to the keyboard to check if the 'D' key is pressed. This works fine, except that it's preventing me from typing into a HTML <input> which resides in another component. I'm guessing it's caused by some piece of code in the keyboard listener class, but I'm not sure where.

Here is the listener class in its entirety:

export class Keyboard {

    private keyboard_d;

    constructor(){
        this.keyboard_d = Keyboard.keyboard(68);
    }

    static keyboard(keyCode){
        var key = {
            code: keyCode,
            isDown: false,
            isUp: true,
            press: undefined,
            release: undefined,
            downHandler: function(event){
                if (event.keyCode === key.code) {
                    if (key.isUp && key.press) key.press();
                    key.isDown = true;
                    key.isUp = false;
                }
                event.preventDefault();
            },
            upHandler: function(event) {
                if (event.keyCode === key.code) {
                    if (key.isDown && key.release) key.release();
                        key.isDown = false;
                        key.isUp = true;
                    }
                    event.preventDefault();
                }
            }

        //Attach event listeners...
        window.addEventListener(
            "keydown", key.downHandler.bind(key), false
        );
        window.addEventListener(
            "keyup", key.upHandler.bind(key), false
        );
        return key;
    }

    //Returns true if the D key is pressed down, false if it is not.
    public isDpressed(){
        return this.keyboard_d.isDown;
    }
}

This class is used in the Angular2 component like this:

var keyboard_listener = new Keyboard(); //create
var dPressed : boolean = keyboard_listener.isDPressed();

Where in this code is it preventing me from typing into HTML input forms?

Note I've purposely left out the Angular code of the two relevant components because I don't want to add the Angular2 tag if I don't need to, my intuition says the code above is the problem. But if it's deemed necessary I'll edit the post and add the Angular code and tag.


Solution

  • The call of event.preventDefault stops the default behaviour of that event and as a result the character is not shown in the input field.