WebMasterCampus
WEB DEVELOPER Resources

Javascript Creating Keyboard Shortcuts

Learn how to use Javascript to create keyboard shortcuts


Javascript Creating Keyboard Shortcuts

Shortcuts are very useful while you want to provide easy access to your appdivcations or provide Navigation access to user. Suppose you want to give shortcut to user when user will press CTRL + R it will execute the application.


<div>Press A key on keyboard (Single key) </div>
<div>Press <strong>Ctrl + Y</strong> shortcut key (Double key combination)</div>
<div>Press <strong>Ctrl + Alt + Z</strong> shortcut key (Multiple key combination)</div>
<div>Press <strong>Ctrl + Alt + Shift + R</strong> shortcut key (Multiple key combination)</div>
<div>Press <strong>Ctrl + Alt + Shift + G</strong> shortcut key (Multiple key combination)</div>

<div id="result"></div>

Now, if you add following script before the closing tag of body tag, it will start capturing keys when key up will trigger. Key up triggers when user release the key. Key press events like keyup, keypress, and keydown events can be used to capture key triggers.


var key = e.key;

e.key will return which letter from the keyboard pressed. Note a and A are different while checking keyboard events.

Similary, ctrlKey, shiftKey and altKey are the read-only properties which hold boolean information about these keys.

<script>
document.addEventListener('keyup', (e) => {

    console.log(e);
    let key = e.key;

    if (key == 'A') {
        document.getElementById("result").innerHTML = "A key was pressed";
    }
    else if (e.ctrlKey && key == 'Y') {
        document.getElementById("result").innerHTML = "Ctrl + Y shortcut key combination was pressed";
    }
    else if (e.ctrlKey && e.altKey && key == 'Z') {
        document.getElementById("result").innerHTML = "Ctrl + Alt + Z shortcut key combination was pressed";
    }
    else if (e.ctrlKey && e.altKey && e.shiftKey && key == 'R') {
        document.getElementById("result").innerHTML = "Ctrl + Alt + Shift + R shortcut key combination was pressed";
    }
    else if (e.ctrlKey && e.altKey && e.shiftKey && key == 'G') {
        document.getElementById("result").innerHTML = "Ctrl + Alt + Shift + G shortcut combination was pressed";
    }
});

<script>
Created with love and passion.