Information



Tags



Share

How to create Keyboard Shortcuts in JavaScript

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement


Best VPN Service
Best VPN


Definition

In this tutorial, I will show you how to create keyboard shortcuts so as to execute associated functions when any pre-defined keyboard shortcut is triggered by the user.

KeyboardEvent Properties and Methods(*)

Property/Method Description
altKey Returns whether the "ALT" key was pressed when the key event was triggered
charCode Returns the Unicode character code of the key that triggered the event
code Returns the code of the key that triggered the event
ctrlKey Returns whether the "CTRL" key was pressed when the key event was triggered
getModifierState() Returns true if the specified key is activated
isComposing Returns whether the state of the event is composing or not
key Returns the key value of the key represented by the event
keyCode Returns the Unicode character code of the key that triggered the onkeypress event, or the Unicode key code of the key that triggered the onkeydown or onkeyup event
location Returns the location of a key on the keyboard or device
metaKey Returns whether the "meta" key was pressed when the key event was triggered
repeat Returns whether a key is being hold down repeatedly, or not
shiftKey Returns whether the "SHIFT" key was pressed when the key event was triggered
which Returns the Unicode character code of the key that triggered the onkeypress event, or the Unicode key code of the key that triggered the onkeydown or onkeyup event

Code

Using the onkeyup event, detect whether a keyboard character is pressed or not.

For run the code cross-browsers, include .which and .keyCode keyboard event methods.

As shown below, if Ctrl + Alt + the trigger key is pressed: proceed the command.

H: Home screen

A: Articles

P: Projects

T: Tools

S: Sign In

document.onkeyup = function myFunction(event) {
  let key = event.which || event.keyCode;
  if(event.ctrlKey && event.altKey && key == 72){
	  window.location = "/";
  }else if(event.ctrlKey && event.altKey && key == 65){
	  window.location = "/articles";
  }else if(event.ctrlKey && event.altKey && key == 80){
	  window.location = "/projects";
  }else if(event.ctrlKey && event.altKey && key == 84){
	  window.location = "/tools";
  }else if(event.ctrlKey && event.altKey && key == 83){
	  window.location = "/SignIn";
  }
}

Result:

Press Ctrl + Alt + H to go to the home page.

Press Ctrl + Alt + A to go to the articles page.

Press Ctrl + Alt + P to go to the projects page.

Press Ctrl + Alt + T to go to the tools page.

Press Ctrl + Alt + S to go to the sign in page.

References

(*) https://www.w3schools.com/jsref/obj_keyboardevent.asp