How to Listen for Keyboard Shortcuts

A guide on how to listen for keyboard events in TypeScript, using Cmd+K or Ctrl+K as a practical example to open a search dialog.

You can make your site feel more like a native app by adding keyboard shortcuts. A common one is using Cmd+K (on Mac) or Ctrl+K (on Windows) to open a search bar.

Imagine you have a search dialog that opens when you click a button. You also want to open it when a user presses Cmd+K.

HTML
<button id="search-button">Open Search</button>
<dialog id="search-box-container">
    <section id="search-box">some box here</section>
</dialog>

You can listen for keyboard events on the entire document. The keydown event is a good choice for shortcuts.

TypeScript
document.addEventListener("DOMContentLoaded", () => {
    const searchDialog = document.querySelector<HTMLDialogElement>(
        "#search-box-container"
    );

    if (searchDialog) {
        document.addEventListener("keydown", (event) => {
            // Check for Cmd+K (Mac) or Ctrl+K (Windows/Linux)
            if ((event.metaKey || event.ctrlKey) && event.key === "k") {
                event.preventDefault(); // Stop the browser from its default behavior
                searchDialog.showModal();
            }
        });
    }
});

How it works:

  1. document.addEventListener("keydown", ...): We attach a listener to the whole document, so it will catch the key press no matter what element is focused.
  2. event.metaKey: This is true if the Cmd key (on Mac) is pressed.
  3. event.ctrlKey: This is true if the Ctrl key (on Windows or Linux) is pressed. By checking for metaKey or ctrlKey, we support both kinds of computers.
  4. event.key === "k": This checks if the key that was pressed was the “k” key.
  5. event.preventDefault(): This is important. Many browsers have their own shortcuts. For example, Cmd+K might focus the browser’s own search bar. preventDefault() tells the browser not to do its default action, so we can run our own code instead.

Other recipes in DOM