Press a Key
Jamie Johnson
April 25, 2018
Want to detect what key is pressed, such as with a JavaScript app where a particular key results in a particular action? Here's how. Press a key and see what happens below:
And how is it detected? It's a relatively short script:
<script>
document.onkeypress=function(e){
whatkey = String.fromCharCode(e.which);
if(e.which==32){whatkey='space';}
if(e.which==13){whatkey='Enter';}
document.getElementById('keyoutput').innerHTML=('You pressed key '+e.which+', which is the '+whatkey+' key.'); // shows which key it is; e.g., 13 is Enter
}
</script>
So now, you can use e.which to determine what happens when a key is pressed. And you can use this tool to determine which character code value goes with which key.
Want more? See my article Press a Key, Too!