snewcomer
snewcomer

Reputation: 2135

When to use KeyboardEvent vs addEventListener for keyup

I've seen examples where to add an event listener, both a KeyboardEvent is created/dispatched and an addEventListener is called. Is there a reason to do both (maybe older IE versions)? Or is simply addEventListener enough to support all browsers + >= IE11.

const keyboard = new KeyboardEvent('keyup', { view: window, bubbles: true, cancelable: true });

document.addEventListener('keyup', _closureMethod, false);

document.dispatchEvent(keyboard);

Upvotes: 0

Views: 443

Answers (1)

Angel Politis
Angel Politis

Reputation: 11313

You are describing two different things:

  • when using addEventListener on keyup, you wait for a keyup event to be triggered by the press of a keyboard button.
  • creating a KeyboardEvent and dispatching it simulates a keyup event. You don't need an event listener for that, because it's an artificial event.

Upvotes: 1

Related Questions