49

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?

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
  • 1
    @Barmar Right, I know what 'deprecated' means. However as I mentioned in the question, I'm looking for any further info on this like what's the recommended replacement (updated the question to state it explicitly). – Alexander Abakumov Oct 18 '18 at 20:49
  • That's in the answer that I posted several minutes ago. – Barmar Oct 18 '18 at 20:50
  • I guess the replacement is keyup https://developer.mozilla.org/en-US/docs/Web/Events/keyup – Mohammed Oct 18 '18 at 20:51
  • @Barmar I see that. Just answering to your comment. – Alexander Abakumov Oct 18 '18 at 20:57
  • 1
    @Mohammed `keyup` is a little bit different, so I'm not sure it's the intended replacement. From Barmar's [answer](https://stackoverflow.com/a/52882269/3345644), it seems to be `beforeinput` instead. – Alexander Abakumov Oct 18 '18 at 21:11

4 Answers4

26

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).

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • There seems to be no data on browser support for `beforeinput` event. MDN has a link to it [here](https://developer.mozilla.org/en-US/docs/Web/API/InputEvent), but the page [doesn't](https://developer.mozilla.org/en-US/docs/Web/Events/beforeinput) exist. Do you have any additional info on this event? – Alexander Abakumov Oct 18 '18 at 21:00
  • Sorry, no. I'd never heard of it myself before pasting that quote. – Barmar Oct 18 '18 at 21:10
  • Thank you, no problem! From what I see, `beforeinput` seems to be so very recently added to the spec that we probably should wait a while and continue using `keypress` until the better adoption. – Alexander Abakumov Oct 18 '18 at 21:15
  • Or you could use `keydown` instead. The decision depends on what you're trying to implement. – Barmar Oct 18 '18 at 21:18
  • 7
    That's true, but `keydown` is a little bit different. In this question, I'm trying to figure out the exact replacement for using when it's time to stop using `keypress`. If spec authors intend `beforeinput` for this purpose, I believe it should be more exact match. – Alexander Abakumov Oct 18 '18 at 21:30
  • It will only be a useful replacement in editing contexts. If you're trying to detect keypresses outside an input field, you'll need to use `keydown`. – Barmar Oct 18 '18 at 21:32
  • Not sure I understand you correctly. At the moment, you have a choice of `keypress` and `keydown`. If you're choosing `keypress` but `keydown` isn't suitable for one of the reasons, you have to replace `keypress` in the future with `beforeinput`, but not with `keydown` (since you refused `keydown` alternative in the first place). That what's in my mind and the intended context of the question. – Alexander Abakumov Oct 18 '18 at 21:47
  • I think the expectation is that `beforeinput` will be implemented soon, long before `keypress` goes away. If you can't use `keydown`, then I guess you're stuck using the deprecated event, and maybe they jumped the gun on deprecating it before there was a good replacement. – Barmar Oct 18 '18 at 21:51
  • 7
    Completely agree with you. Very disappointing that `keypress` is deprecated so early when there is actually no direct replacement provided in the real world leaving developers with the tough choice on their own. – Alexander Abakumov Oct 18 '18 at 21:57
  • 2
    @AlexanderAbakumov - That's the point of deprecation though, to warn users to avoid using the feature, in this case because it has interoperability problems. The reality is, of course, that no mainstream browser will ever stop implementing keypress, because doing so would break a large swathe of existing websites. All it means at present is that you should start thinking about how to use a combination of keydown, beforeinput, input, and keyup events instead. You could seek to detect beforeinput support and use it if it is available, falling back to keypress otherwise. – Alohci Oct 19 '18 at 00:54
  • 9
    @Alohci Thank you. Just to make it more clearly, I'm not againt this deprecation in general. But the really nasty part of this specific situation is that it's deprecated too early. A deprecation is good only after providing a replacement that's doable practically with comparable level of effort. I believe no dev team having working apps with `keypress` (which is the most popular option for restricting character set for `inputs`) would try messing with `keydown`, `input`, and `keyup` events just because `beforeinput` isn't available yet. – Alexander Abakumov Oct 19 '18 at 14:18
  • 5
    This answer doesn't address specific use cases such as Alt key sequences in Windows, where the resulting keycode (for instance `ë` for Alt+137) gets a `keypress` event, but not a `keyup` or `keydown` one. Only the individual keys `1`, `3` and `7` are reported as keyup and keydown, but not the `ë`. So they can deprecate it all they want, but unlewss they offer a real alternative, we naive front-end developers have no choice but to use `keypress`. – Mr Lister Mar 06 '20 at 20:12
  • @MrLister That's similar to the point I made in my last paragraph: If none of the supported events works for you, you're stuck with this. – Barmar Mar 06 '20 at 20:18
  • Just to note: `beforeinput` is ***useless*** if you are trying to capture key events in an element that is not an input or textarea. Guess I'm stuck using a deprecated feature for new code because I just can't find a reliable way to otherwise know if an event corresponds to an actual *character* or not... – Michael Jul 03 '22 at 18:26
7
 const handleKeyDown = (e: any) => {
  if (e.code === "Enter") {
  triggerBusqueda(e.target.value);
  }
};

onKeyDown={handleKeyDown}

You can use this code, it works very well.

2

onKeyPress is deprecated. enter image description here

It has been replaced by onKeyDown

onKeyPress={(e) => {
  if (e.key === 'Enter') {
    createInvitationF()
  }
}}

is replaced by

onKeyDown={(e) => {
  if (e.key === 'Enter') {
    createInvitationF()
  }
}}
Alan
  • 9,167
  • 4
  • 52
  • 70
-6

Not super hard to work around unless (shame on you) you or something you use has been clobbering event bubbling indiscriminately at every opportunity.

Simple but powerful utility like this is exactly why you should only do that for isolated node leaves of your HTML.

In those cases where you did have to prevent keydown bubbling you could simply wrap the following in a function that takes an argument in place of document.body and simply apply at the point where bubbling is stopped if you still want 'keypress2' events available to that HMTL.

const keyBlacklist = [
    'Shift',
    'Alt',
    'Control',
    'Meta'
];

document.body.addEventListener('keydown',(e)=>{
    if(keyBlacklist.indexOf(e.key) === -1){
        const newKeyPress = new CustomEvent('keypress2',{detail:e});
        e.target.dispatchEvent(newKeyPress);
    }
});

document.body.addEventListener('keypress2',e=>{console.log(e.detail);});
Erik Reppen
  • 4,605
  • 1
  • 22
  • 26
  • 7
    This answer doesn't address specific use cases such as Alt key sequences in Windows, where the resulting keycode (for instance `ë` for Alt+137) gets a `keypress` event, but not a `keyup` or `keydown` one. Only the individual keys `1`, `3` and `7` are reported as keyup and keydown, but not the `ë`. So they can deprecate it all they want, but unlewss they offer a real alternative, we naive front-end developers have no choice but to use `keypress`. – Mr Lister Mar 06 '20 at 20:13