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);
});
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
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;
});
| Goal | Prefer |
|---|---|
| React to a specific keyboard key | keydown + event.key |
| React after a key is released | keyup |
| React to a field value changing | input |
| Inspect or intercept text before insertion | beforeinput |
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.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| user | 03-04-2015 |
| thank you very much... | |