Skip to content

Instantly share code, notes, and snippets.

@MirzaLeka
Last active July 16, 2023 19:05
Show Gist options
  • Save MirzaLeka/ebaefc9aad994c285de43d0aa1282055 to your computer and use it in GitHub Desktop.
Save MirzaLeka/ebaefc9aad994c285de43d0aa1282055 to your computer and use it in GitHub Desktop.
Trigger Javascript event on keypress without input or button

Trigger Javascript event on keypress without input or button

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.

Create function in Javascript:

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.
  
     }

Summary:

  • 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment