JavaScript keypress Event: Legacy Reference and Modern Alternatives

Legacy API: The keypress event is deprecated. Keep it only when maintaining older code. For new JavaScript, use keydown for key actions or beforeinput/input for text entry.

Older JavaScript commonly attached an onkeypress handler to a text field. The event mainly represented character-producing keys and did not provide a consistent modern model for every keyboard key.

// Legacy pattern
input.onkeypress = function () {
  // old keypress handler
};

// Modern key action
input.addEventListener('keydown', (event) => {
  console.log(event.key);
});
Table of Contents

How the Old keypress Event Worked Top ↑

The original plus2net example copied a text field’s current value during keypress. Because the event could occur before the browser inserted the new character, the copied value could appear one character behind.

Legacy keypress timing demo Legacy event-listener version

Why the Copied Text Can Lag Top ↑

Keyboard events describe key activity; text-editing events describe changes to a control’s value. If your requirement is “run after the field value changes,” use input rather than choosing a keyboard event merely for timing.

const input = document.getElementById('t1');
const output = document.getElementById('t2');

input.addEventListener('input', () => {
  output.value = input.value;
});

Which Event Should Replace keypress? Top ↑

GoalPrefer
React to a specific keyboard keykeydown + event.key
React after a key is releasedkeyup
React to a field value changinginput
Inspect or intercept text before insertionbeforeinput

Migrating Old onkeypress Code Top ↑

Remove the inline onkeypress attribute, select the element in JavaScript, attach the appropriate modern event with addEventListener(), and replace keyCode/which checks with event.key where the goal is key identification.

See getElementById() for element selection. Continue with keydown or return to Event Handling.




Subscribe to our YouTube Channel here



plus2net.com







user

03-04-2015

thank you very much...



We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer