Categories
JavaScript Answers

How to Handle Function KeyPress Events (F1-F12) using JavaScript?

Spread the love

Sometimes, we want to handle function keypress events (F1-F12) using JavaScript.

In this article, we’ll look at how to handle function keypress events (F1-F12) using JavaScript.

Handle Function KeyPress Events (F1-F12) using JavaScript

To handle function keypress events (F1-F12) using JavaScript, we can add a key-down event handler.

And in it, we call preventDefault to stop the default action from executing.

And then we can do what we want instead when a function key is pressed.

For instance, we can write:

window.onkeydown = (evt) => {  
  switch (evt.keyCode) {  
    //ESC  
    case 27:  
      evt.preventDefault();  
      console.log("esc");  
      break;  
    //F1  
    case 112:  
      evt.preventDefault();  
      console.log("f1");  
      break;  
    default:  
      return;  
  }  
};

to set the window.onkeydown property to an event handler that checks what the keyCode property is pressed with a switch statement.

keyCode returns a numeric code for the key that’s pressed.

Keycode 27 is the escape key, and 112 is the F1 key.

We call evt.preventDefault to stop the default action in each case clause.

So pressing F1 will stop the help screen from displaying and will log 'f1' instead.

Conclusion

To handle function keypress events (F1-F12) using JavaScript, we can add a key-down event handler.

And in it, we call preventDefault to stop the default action from executing.

And then we can do what we want instead when a function key is pressed.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *