SyntaxStudy
Sign Up
jQuery Intermediate 4 min read

Keyboard Shortcuts

Keyboard Shortcuts

Bind application-wide keyboard shortcuts with jQuery, respecting input field focus to avoid conflicts.

Example
$(document).on("keydown", function(e) {
  // Ignore when typing in input/textarea
  if ($(e.target).is("input,textarea,select,[contenteditable]")) return;
  const key = (e.ctrlKey || e.metaKey ? "ctrl+" : "") + (e.shiftKey ? "shift+" : "") + e.key.toLowerCase();
  const shortcuts = {
    "ctrl+k": () => $("#search").focus().select(),
    "ctrl+/": () => showShortcutHelp(),
    "?":      () => showShortcutHelp(),
    "g h":    () => navigate("/"),
    "escape": () => $(".modal.show").modal("hide"),
  };
  if (shortcuts[key]) { shortcuts[key](); e.preventDefault(); }
});
Pro Tip

Always ignore shortcuts when an input is focused — typing "g" should not trigger navigation.