Typescript global keystate

Date: 2024-03-04
export interface IKeyStates {
    control: boolean;
    shift: boolean;
    alt: boolean;
}

class KeyStateProvider {
    register() {
        const keyStates: IKeyStates = {
            control: false,
            shift: false,
            alt: false
        };

        let element: HTMLElement = window.document.body;
        element.addEventListener("keydown", function (event) {
            if (event.key === "Alt")
                keyStates.alt = true;
            if (event.key === "Control")
                keyStates.control = true;
            if (event.key === "Shift")
                keyStates.shift = true;
        });
        element.addEventListener("keyup", function (event) {
            if (event.key === "Alt")
                keyStates.alt = false;
            if (event.key === "Control")
                keyStates.control = false;
            if (event.key === "Shift")
                keyStates.shift = false;
        });

        this.keyStates = keyStates;
    }
    keyStates: IKeyStates;

    constructor() {
        this.keyStates = {
            control: false,
            alt: false,
            shift: false
        };
        this.register();
    }
}

export const keyStateProvider = new KeyStateProvider();



// usage:
import { keyStateProvider } from "./helpers/KeyStateProvider";

if (keyStateProvider.keyStates.control) {
    // control is pressed
}



83330cookie-checkTypescript global keystate