Normally when I wanted to catch an event on a page in js:
window.onkeydown = function (event) {
//Do something here
}
I cannot seem to figure out (or Google) how to do this in typescript. For the setup I am working in, there is a ts
file for the page, and a ts
file for the class that it is loading.
Syntax of addEventListener() method object. addEventListener(event, function, useCapture); Here, the first parameter, “event” is added to specify the event for which you want to add the event handler; the second parameter, “function” invokes the function that will be executed when the specified event occurs.
You can add event listeners to any DOM object not only HTML elements. i.e the window object. The addEventListener() method makes it easier to control how the event reacts to bubbling.
This
window.addEventListener('keydown', keyDownListener, false)
window
is defined will all events in lib.d.ts
and this particular listener as
addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void;
or this, if you want to keep your original "style",
window.onkeydown = (ev: KeyboardEvent): any => {
//do something
}
To answer more clearly:
const controlDown = (event: KeyboardEvent) => {
console.log(event);
};
window.addEventListener('keydown', controlDown);
windows.addEventListener('keydown', (event: KeyboardEvent) =>{
// if you need event.code
});
windows.addEventListener('keydown', (event: Event) =>{
// event
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With