Back to Snippets

macOS Style Command Palette Modal JS

Press Cmd+K on a Mac or Ctrl+K elsewhere to open a centered search modal. Escape closes it, clicking the dark area around it closes it, and the same shortcut toggles it shut again.

One keydown listener on window handles all of that. It checks metaKey or ctrlKey alongside the k key and calls preventDefault, which is what stops Chrome and Firefox claiming the shortcut for their own search. Opening moves focus into the input so you can start typing straight away.

Clicking outside works by testing that the click target is the backdrop element itself rather than anything inside the modal, which avoids the usual bug where selecting a list item closes the panel. The command list is static markup and the input does not filter it yet, so wire that up to your own data before shipping it.

255
#javascript
#css
#command palette
#macos
#modal
#search
#keyboard shortcut
#glassmorphism
#ui