Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacement for deprecated `keypress` DOM event

According to MDN article keypress event is deprecated:

enter image description here

But I can't find any information elsewhere on whether we should use this event in a new projects. If we shouldn't, what is the replacement?

Could somebody give an insight?

like image 606
Alexander Abakumov Avatar asked Oct 18 '18 20:10

Alexander Abakumov


2 Answers

Since the event is deprecated, you should avoid using it in new code, and plan on removing it from old code. The W3C specification says this about deprecated features:

Features marked as deprecated are included in the specification as reference to older implementations or specifications, but are OPTIONAL and discouraged. Only features which have existing or in-progress replacements MUST be deprecated in this specification. Implementations which do not already include support for the feature MAY implement deprecated features for reasons of backwards compatibility with existing content, but content authors creating content SHOULD NOT use deprecated features, unless there is no other way to solve a use case. Other specifications which reference this specification SHOULD NOT use deprecated features, but SHOULD point instead to the replacements of which the feature is deprecated in favor. Features marked as deprecated in this specification are expected to be dropped from future specifications.

The specification of the keypress event says:

Warning The keypress event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type. When in editing contexts, authors can subscribe to the beforeinput event instead.

You can also use the keydown and/or keyup events. See What's the difference between keyup, keydown, keypress and input events?

However, since beforeinput doesn't yet have much support, if none of these other events fits your use case you'll have to continue to use keypress for now (that's the "unless there is no other way to solve a use case" exception in the spec).

like image 61
Barmar Avatar answered Sep 16 '22 23:09

Barmar


You could use keydown event. Unlike the keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value.

const log = document.getElementById('log');

document.addEventListener('keydown', logKey);

function logKey(e) {
  log.textContent += ` ${e.code}`;
}
<p>Focus the IFrame first (e.g. by clicking in it), then try pressing some keys.</p>
<p id="log"></p>
like image 45
MD SHAYON Avatar answered Sep 19 '22 23:09

MD SHAYON