1

I want to trigger a javascript function whenever a specific key is pressed on the keyboard, for example

After pressing button "A" on the keyboard, run the function "myFunction()"

function myFunction() {
  alert("hey");
}
m24197
  • 1,038
  • 1
  • 4
  • 12
  • 2
    So bind event listener and check key – epascarello Apr 07 '21 at 18:06
  • 1
    Begin by trying to solve the problem yourself; post any specific problems or questions you run into. – junvar Apr 07 '21 at 18:09
  • 1
    Does this answer your question? [Trigger a button click with JavaScript on the Enter key in a text box](https://stackoverflow.com/questions/155188/trigger-a-button-click-with-javascript-on-the-enter-key-in-a-text-box) – steven7mwesigwa Apr 07 '21 at 18:22
  • Does this answer your question? [JS function when keyboard key is pressed?](https://stackoverflow.com/questions/14261062/js-function-when-keyboard-key-is-pressed) – Heretic Monkey Apr 07 '21 at 18:30

1 Answers1

3
Something similar   
 
<script>
document.addEventListener("keydown", event => {
  if (event.isComposing || event.keyCode !== 65) {
    return;
  }
  myFunction();
});
function myFunction() {
  alert("hey");
}
</script>
JohntheTyro
  • 136
  • 4