Javascript onKeyPress example

Example code for onKeyPress method for handling keyboard key press

by Mostafiz Rahman

HTML

<body>

<p>This example demonstrates how to assign an "onkeypress" event to an input element.</p>

<p>Press a key inside the text field to set a red background color.</p>

<input type="text" id="demo" onkeypress="myFunction(event)">

<script>
function myFunction(e) {
	if(e.key == 'Enter')
    document.getElementById("demo").style.backgroundColor = "red";
  else if(e.key == 'a')
    document.getElementById("demo").style.backgroundColor = "blue";
   else if(e.key == 'b')
    document.getElementById("demo").style.backgroundColor = "green";
}
</script>

</body>