Skip to content

Instantly share code, notes, and snippets.

@Roy-Orbison
Last active April 12, 2023 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Roy-Orbison/34c7237527be8827ed8be56f21aa967b to your computer and use it in GitHub Desktop.
Save Roy-Orbison/34c7237527be8827ed8be56f21aa967b to your computer and use it in GitHub Desktop.
A contrived example to demonstrate that you can listen for "/" as a shortcut key *and* still fall back to the native Quick Find, so your site does not completely commandeer a useful browser feature.
<input type=search placeholder=search><br>
<textarea placeholder="won't respond to / shortcut"></textarea>
<script>
document.addEventListener(
'keydown',
(function() {
let lastWasSlash = false,
thisIsSlash,
input = document.querySelector('input');
return evt => {
thisIsSlash = evt.key == '/' && !(
evt.altKey
|| evt.ctrlKey
|| evt.isComposing
|| evt.metaKey
|| evt.shiftKey
);
if (thisIsSlash)
switch (document.activeElement) {
case document.body:
evt.preventDefault();
input.focus();
break;
case input:
if (lastWasSlash && !input.value)
input.blur();
break;
default:
if (lastWasSlash)
lastWasSlash = false;
return;
}
lastWasSlash = thisIsSlash;
};
})(),
{
capture: true
}
);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment