Skip to content

Instantly share code, notes, and snippets.

@metodribic
Created October 13, 2020 06:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save metodribic/641afe6f5eeb3c9f6faf3574a08bb23d to your computer and use it in GitHub Desktop.
Save metodribic/641afe6f5eeb3c9f6faf3574a08bb23d to your computer and use it in GitHub Desktop.
Utils for dealing with keyboard events and figuring out what was pressed
export const enum KeyCodes {
BACKSPACE = 8,
TAB = 9,
ENTER = 13,
SPACE = 32,
DELETE = 46
}
export class EventUtil {
/**
* Util for checking if pressed key is number
*/
static isNumberKey(key): boolean {
if (key >= 96 && key <= 105) {
// Num pad keys
key -= 48;
}
return key > 47 && key < 58;
}
/**
* Check if pressed key is arrow key
*/
static isArrowKey(key: number): boolean {
return key > 36 && key < 41;
}
/**
* Check if press key is allowed
*/
static isAllowedKeyType(event): boolean {
const keyCode = event.keyCode;
return event.metaKey || event.ctrlKey ||
event.altKey || event.shiftKey ||
keyCode === KeyCodes.TAB ||
keyCode === KeyCodes.DELETE ||
keyCode === KeyCodes.BACKSPACE ||
keyCode === KeyCodes.ENTER;
}
/**
* Check if Delete or Backspace
*/
static isRemoveKey(pressedKeyCode): boolean {
return pressedKeyCode === KeyCodes.DELETE || pressedKeyCode === KeyCodes.BACKSPACE;
}
/**
* Check if pressed button is control or command
*/
static isMetaOrCtrlKey(event): boolean {
return event.metaKey || event.ctrlKey;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment