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:
document.addEventListener("keydown", ...): We attach a listener to the whole document, so it will catch the key press no matter what element is focused.event.metaKey: This istrueif theCmdkey (on Mac) is pressed.event.ctrlKey: This istrueif theCtrlkey (on Windows or Linux) is pressed. By checking formetaKeyorctrlKey, we support both kinds of computers.event.key === "k": This checks if the key that was pressed was the “k” key.event.preventDefault(): This is important. Many browsers have their own shortcuts. For example,Cmd+Kmight 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.