Tagged: web development

Unlock JavaScript Key Code Values for Developers

I have a mountain of unpublished blog posts. I can now use AI to make more sense of all of this content. So, I decided to start cleaning up the posts and releasing them in a series I’m calling “Throwback Tuesdays”. I aim to make them relevant for today as best I can. However, I will publish even if it’s a dead concept.

First up, JavaScript ASCII Key Code Values from January 2015. I was struggling to find key codes and got a list of values from Rachit Patel (see the end of this post for the list). This was just a reference post so I didn’t have to dig through Google search results to find a key code. This is somewhat useless today with all the ready made code and AI that can crank out solutions that are based on key codes.

Unlocking the Power of Keyboard Shortcuts in Web Applications

Why did I need a list of key codes? I needed to make keyboard shortcuts for various use cases. Let’s explore the possibilities.

Keyboard shortcuts are an essential tool for enhancing user experience and interaction in web applications. By responding to key presses, developers can create intuitive and powerful functionality, ranging from custom navigation to accessibility features. Below, we explore examples of why and how these shortcuts can be used, complete with code and explanations to inspire your next project.


Form Navigation

Use Case: Improve user experience by enabling seamless navigation between input fields.

Code:

document.addEventListener('keydown', (event) => {
    if (event.keyCode === 9) { // Tab key
        event.preventDefault();
        const inputs = Array.from(document.querySelectorAll('input, textarea'));
        const current = inputs.indexOf(document.activeElement);
        const next = (current + 1) % inputs.length;
        inputs[next].focus();
    }
});

Explanation:

  • Listens for the Tab key press (keyCode 9).
  • Prevents the default behavior and cycles focus through input and textarea fields in a custom order.

Custom Keyboard Shortcuts

Use Case: Provide power users with quick access to application features.

Code:

document.addEventListener('keydown', (event) => {
    if (event.ctrlKey && event.keyCode === 83) { // Ctrl+S
        event.preventDefault();
        console.log('Save shortcut triggered');
    }
});

Explanation:

  • Detects when the Ctrl key is pressed along with S (keyCode 83).
  • Prevents the browser’s default save dialog and triggers custom functionality, such as saving data.

Game Controls

Use Case: Enable interactive movement in games or apps.

Code:

document.addEventListener('keydown', (event) => {
    switch (event.keyCode) {
        case 37: // Left arrow
            console.log('Move left');
            break;
        case 38: // Up arrow
            console.log('Move up');
            break;
        case 39: // Right arrow
            console.log('Move right');
            break;
        case 40: // Down arrow
            console.log('Move down');
            break;
    }
});

Explanation:

  • Maps arrow keys to movement directions (left, up, right, down).
  • Switch statements check the keyCode and trigger corresponding actions.

Text Editor Commands

Use Case: Allow users to insert a tab character in text areas.

Code:

document.addEventListener('keydown', (event) => {
    if (event.keyCode === 9) { // Tab key
        event.preventDefault();
        const editor = document.getElementById('editor');
        const start = editor.selectionStart;
        editor.value = editor.value.slice(0, start) + '\t' + editor.value.slice(start);
        editor.selectionStart = editor.selectionEnd = start + 1;
    }
});

Explanation:

  • Overrides the default Tab key behavior to insert a tab character (\t) at the cursor position in a text editor.

Secret Feature Activation

Use Case: Trigger hidden features using specific key sequences.

Code:

let secretSequence = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65]; // Konami Code
let inputSequence = [];

document.addEventListener('keydown', (event) => {
    inputSequence.push(event.keyCode);
    if (inputSequence.slice(-secretSequence.length).join('') === secretSequence.join('')) {
        console.log('Secret mode activated!');
    }
});

Explanation:

  • Tracks user key presses and compares them to a predefined sequence (e.g., the Konami Code).
  • Executes an action when the sequence is completed.

Virtual Keyboard Input

Use Case: Mimic physical keyboard input for touchscreen devices.

Code:

const virtualKeys = document.querySelectorAll('.virtual-key');
virtualKeys.forEach((key) => {
    key.addEventListener('click', () => {
        const keyCode = parseInt(key.dataset.keyCode, 10);
        const event = new KeyboardEvent('keydown', { keyCode });
        document.dispatchEvent(event);
    });
});

Explanation:

  • Creates virtual keys that simulate real key presses by dispatching synthetic keydown events.
  • Useful for applications that run on touchscreen devices.

Accessibility Features

Use Case: Provide shortcuts to assist users with disabilities.

Code:

document.addEventListener('keydown', (event) => {
    if (event.keyCode === 16) { // Shift key
        console.log('Accessibility shortcut triggered');
    }
});

Explanation:

  • Detects the Shift key press (keyCode 16) and performs an action, such as enabling high-contrast mode.

Media Controls

Use Case: Control video playback using the keyboard.

Code:

document.addEventListener('keydown', (event) => {
    const video = document.getElementById('videoPlayer');
    if (event.keyCode === 32) { // Spacebar
        video.paused ? video.play() : video.pause();
    } else if (event.keyCode === 37) { // Left arrow
        video.currentTime -= 5;
    } else if (event.keyCode === 39) { // Right arrow
        video.currentTime += 5;
    }
});

Explanation:

  • Spacebar toggles play/pause, while the left and right arrow keys adjust the playback position.

Form Validation

Use Case: Restrict input to numeric values only.

Code:

document.getElementById('numberInput').addEventListener('keydown', (event) => {
    if ((event.keyCode < 48 || event.keyCode > 57) && // Numbers 0-9
        (event.keyCode < 96 || event.keyCode > 105)) { // Numpad 0-9
        event.preventDefault();
    }
});

Explanation:

  • Prevents non-numeric keys from being entered, ensuring valid input.

Fullscreen or Escape

Use Case: Toggle fullscreen mode or close a modal.

Code:

document.addEventListener('keydown', (event) => {
    if (event.keyCode === 27) { // Escape
        console.log('Modal closed');
    } else if (event.keyCode === 122) { // F11
        event.preventDefault();
        document.documentElement.requestFullscreen();
    }
});

Explanation:

  • Escape key closes modals or cancels actions.
  • F11 toggles fullscreen mode, overriding default behavior.

Conclusion

By leveraging keyboard shortcuts, developers can create applications that are not only more user-friendly but also highly functional and accessible. These examples range from form navigation to hidden features. They demonstrate how key presses can enhance interactivity and usability in your web applications. Explore these ideas in your own projects to deliver delightful and intuitive user experiences.

JavaScript ASCII Key Code Values

KeyCode

backspace

8

tab

9

enter

13

shift

16

ctrl

17

alt

18

pause/break

19

caps lock

20

escape

27

page up

33

page down

34

end

35

home

36

left arrow

37

up arrow

38

right arrow

39

down arrow

40

insert

45

delete

46

0

48

1

49

2

50

3

51

4

52

5

53

6

54

7

55

8

56

9

57

a

65

b

66

c

67

d

68

e

69

f

70

g

71

h

72

i

73

j

74

k

75

l

76

m

77

n

78

o

79

p

80

q

81

r

82

s

83

t

84

u

85

v

86

w

87

x

88

y

89

z

90

left window key

91

right window key

92

select key

93

numpad 0

96

numpad 1

97

numpad 2

98

numpad 3

99

numpad 4

100

numpad 5

101

numpad 6

102

numpad 7

103

numpad 8

104

numpad 9

105

multiply

106

add

107

subtract

109

decimal point

110

divide

111

f1

112

f2

113

f3

114

f4

115

f5

116

f6

117

f7

118

f8

119

f9

120

f10

121

f11

122

f12

123

num lock

144

scroll lock

145

semi-colon

186

equal sign

187

comma

188

dash

189

period

190

forward slash

191

grave accent

192

open bracket

219

back slash

220

close braket

221

single quote

222