How to Use onkeydown, onkeypress and onkeyup HTML Event Listeners

HTML event liseteners onkeydown, onkeypress and onkeyup will only be called on HTML elements that can be focused, sush as inputs, buttotn or anchor tags. If an anchor is not assigned with any target, it cannot be focused.
The order of execution for onkeydown, onkeypress and onkeyup is onkeydown, onkeypress and onkeyup.
<input onkeydown="show.innerHTML = 'keydown, '" onkeypress="show.innerHTML += 'keypress, '" onkeyup="show.innerHTML += 'keyup'" />
<div id="show"></div>

When do I Use onkeyup

I sue onkeyup event listener when I set an input to accept only numbers. As in this article, I wrote about inputs with type number can still be tryped in abnormal numbers suash 00123 or 14-4-1.
I can use onkeydown or onkeypress in this validation, because I would not be able to type in negative numbers
Try the following inputs to see the different effect, I also include oninput eveent listenr which fires after onkeypress.
<input onkeydown="this.value = this.value == 'NaN'? '': parseFloat(this.value)" type="number" />



<input onkeypress="this.value = this.value == 'NaN'? '': parseFloat(this.value)" type="number" />



<input oninput="this.value = this.value == 'NaN'? '': parseFloat(this.value)" type="number" />



<input onkeyup="this.value = this.value == 'NaN'? '': parseFloat(this.value)" type="number" />



You can also make password shown when typing

<input onkeydown="show_2.innerHTML = 'keydown in input, '" />
<div id="show_2"></div>
<script>
window.onkeydown = function(){show_2.innerHTML += 'keydown in window.'}
window.onkeypress = function(){show_3.innerHTML = 'keydown in window, '}
</script>

What about window onkeydown?

By default if both an input and window have defined onkeydonw event listeners, the input one will be trigger before the window one.

You can chage the order of execution by setting onkeyup envent for the input and onkeydown or on keypress with the window obect or any oreder that allows key event to be trigged with window object first.

One more thing, if you keep the key down, the onkeydown and onkeypress will be continuously executed alternatively.

Comments

Popular posts from this blog

How to Make A Reusable Image Slideshow HTML Component With Vanilla JavaScript

HTML Tags and Inline CSS that Work In Plotly.js Title

How to Type Spaces In HTML Input And Display In the Browser