The keyup event fires when the user releases a key. Because the key’s normal text-entry action has already happened, keyup can read the field’s updated value.
const input = document.querySelector('#keyupInput');
input.addEventListener('keyup', (event) => {
console.log(input.value);
console.log(event.key);
});
keyup happens after a pressed key is released. This makes it different from keydown, which runs when the key goes down, and from the legacy keypress event.
If the user typed a character into a text field, that character is normally already present in input.value by the time keyup fires. That is why the original plus2net keyup copy example includes the most recent character.
For reacting to text changes, the input event is often even better because it also covers pasting, speech input and other edits that do not depend on releasing a keyboard key. Use keyup when the release of a specific key is itself important.
input.addEventListener('input', () => {
output.textContent = input.value;
});
The plus2net inches-to-centimeters converter is an example of reacting as a user changes a value. For modern form calculators, input is generally preferable when every value change should update immediately.
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.