Last active
April 12, 2023 07:58
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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