Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding window.event handler to typescript

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.

like image 603
TopBanana9000 Avatar asked Jul 29 '16 13:07

TopBanana9000


People also ask

How do I add an event listener to the window object?

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.

Can you add event listener to window?

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.


3 Answers

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
}
like image 84
Bruno Grieder Avatar answered Oct 17 '22 16:10

Bruno Grieder


To answer more clearly:

const controlDown = (event: KeyboardEvent) => {
    console.log(event);
};
window.addEventListener('keydown', controlDown);
like image 30
manu Avatar answered Oct 17 '22 17:10

manu


windows.addEventListener('keydown', (event: KeyboardEvent) =>{
 // if you need event.code
});

windows.addEventListener('keydown', (event: Event) =>{
 // event
});
like image 28
Ángela Franco Avatar answered Oct 17 '22 16:10

Ángela Franco