Keyboard Events

Handle keyboard input events

BeginnerTopic: Events Programs
Back

JavaScript Keyboard Events Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
// Method 1: Keydown event
document.addEventListener('keydown', function(e) {
    console.log('Key pressed:', e.key);
    console.log('Key code:', e.keyCode);
    console.log('Code:', e.code);
});

// Method 2: Keyup event
document.addEventListener('keyup', function(e) {
    console.log('Key released:', e.key);
});

// Method 3: Keypress event (deprecated, use keydown)
document.addEventListener('keypress', function(e) {
    console.log('Character:', e.key);
});

// Method 4: Specific keys
document.addEventListener('keydown', function(e) {
    if (e.key === 'Enter') {
        console.log('Enter pressed');
    } else if (e.key === 'Escape') {
        console.log('Escape pressed');
    } else if (e.key === 'ArrowUp') {
        console.log('Arrow up');
    }
});

// Method 5: Modifier keys
document.addEventListener('keydown', function(e) {
    if (e.ctrlKey && e.key === 's') {
        e.preventDefault();
        console.log('Ctrl+S pressed - Save');
    }
    
    if (e.shiftKey && e.key === 'Enter') {
        console.log('Shift+Enter');
    }
    
    if (e.altKey && e.key === 'f') {
        console.log('Alt+F');
    }
    
    if (e.metaKey && e.key === 'k') {
        console.log('Cmd+K (Mac) or Ctrl+K');
    }
});

// Method 6: Input field keyboard events
const input = document.getElementById('myInput');

input.addEventListener('keydown', function(e) {
    if (e.key === 'Enter') {
        console.log('Form submitted');
    }
});

input.addEventListener('keyup', function(e) {
    console.log('Input value:', e.target.value);
});

// Method 7: Prevent default for specific keys
document.addEventListener('keydown', function(e) {
    // Prevent spacebar from scrolling
    if (e.key === ' ' && e.target.tagName !== 'INPUT') {
        e.preventDefault();
    }
    
    // Prevent F5 refresh
    if (e.key === 'F5') {
        e.preventDefault();
    }
});

// Method 8: Keyboard shortcuts
const shortcuts = {
    'ctrl+k': () => console.log('Search'),
    'ctrl+s': () => console.log('Save'),
    'ctrl+z': () => console.log('Undo'),
    'ctrl+shift+z': () => console.log('Redo')
};

document.addEventListener('keydown', function(e) {
    const key = e.key.toLowerCase();
    let shortcut = '';
    
    if (e.ctrlKey) shortcut += 'ctrl+';
    if (e.shiftKey) shortcut += 'shift+';
    if (e.altKey) shortcut += 'alt+';
    
    shortcut += key;
    
    if (shortcuts[shortcut]) {
        e.preventDefault();
        shortcuts[shortcut]();
    }
});
Output
// Output depends on keyboard input

Understanding Keyboard Events

Keyboard events handle user input.

Event Types

keydown: Key pressed down
keyup: Key released
keypress: Character typed (deprecated)

Event Properties

key: Character value
keyCode: Numeric code (deprecated)
code: Physical key code
ctrlKey/shiftKey/altKey/metaKey: Modifiers

Common Keys

Enter, Escape, Arrow keys
Space, Tab, Backspace
Function keys (F1-F12)

Use Cases

Keyboard shortcuts
Form validation
Game controls
Accessibility

Best Practices

Use key instead of keyCode
Check modifier keys
Prevent default when needed

Let us now understand every line and the components of the above program.

Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.

Practical Learning Notes for Keyboard Events

This JavaScript program is part of the "Events Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents