Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate an Escape key press in pure Typescript (w/o JQuery)

I am trying to fire an Escape button press event in Angular unit tests.

    const event = document.createEvent('UIEvent');
    event.initUIEvent('keydown', true, true, window, 0);
    (<any>event).keyCode = 27;
    (<any>event).key = 'Escape';
    (<any>event).charCode = 27;

    document.body.dispatchEvent(event);

This does not work at all (event is never caught by listeners that do proper checking like event.which == 27).

What is the correct way to create such an event?

I tried this one too, in vain

    const event = new Event('keydown', {bubbles: true});
    event.initEvent('keydown', true, true);
    (<any>event).keyCode = 27;
    (<any>event).key = 'Escape';
    (<any>event).charCode = 27;

    document.body.dispatchEvent(event);
like image 982
dmitri1122 Avatar asked Oct 28 '25 05:10

dmitri1122


1 Answers

You only need to use a keyboard Event on document or on an element

     const event = new KeyboardEvent("keydown",{
     'key': 'Escape'
     });
     document.dispatchEvent(event);

You can test it with HostListener

@HostListener('document:keydown', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
    console.log(event);
    let keyPressed = event.keyCode;
    if (keyPressed === 27) {
       console.log('Escape!');
    }
}
like image 146
macvag Avatar answered Oct 29 '25 19:10

macvag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!