Open HTML document and find a body tag. Give the body tag onkeypress attribute. It shoud look like this:
<body onkeypress="KeyPressCheck(event)">
...html code...
</body>
Once that's done head over to your Javascript file that you'll import inside the html file with <script>
tag.
Function can be named however you like. In this case function is called KeyPressCheck.
function KeyPressCheck(event){
// This function will be called whenever ANY key on keyboard is pressed.
// if you want to do certain action only whenever Certain key is pressed, just put an if statement as below:
if (event.keyCode == 44) {
// code inside this if statement will execute only when key with ASCII code 44 is pressed.
// that should be DEL key on your keyboard.
// P.S. if you want to remove element when DEL key is pressed, try one of these two:
// el.parentNode.removeChild(el); // Javascript
// $(el).remove(); // Jquery
}
// You can do the same with all the other keys. No input tag needed.
}
- Add onkeypress attribute to your body tag in HTML calling the function you want with event as an argument.
- Create function with the same name in Javascript and it will be called whenever ANY key is pressed.