diff options
-rw-r--r-- | assets/search.js | 23 | ||||
-rw-r--r-- | layouts/partials/docs/search.html | 2 |
2 files changed, 24 insertions, 1 deletions
diff --git a/assets/search.js b/assets/search.js index 9b1c5ab..e064a14 100644 --- a/assets/search.js +++ b/assets/search.js @@ -10,6 +10,29 @@ input.addEventListener('focus', init); input.addEventListener('keyup', search); + document.addEventListener('keypress', focusSearchFieldOnKeyPress); + + function focusSearchFieldOnKeyPress(e) { + if (input === document.activeElement) { + return; + } + + const characterPressed = String.fromCharCode(e.charCode); + if (!isHotkey(characterPressed)) { + return; + } + + input.focus(); + e.preventDefault(); + } + + function isHotkey(character) { + const dataHotkeys = input.getAttribute('data-hotkeys') || ''; + const hotkeys = dataHotkeys.split(' '); + + return dataHotkeys.indexOf(character) >= 0; + } + function init() { input.removeEventListener('focus', init); // init once input.required = true; diff --git a/layouts/partials/docs/search.html b/layouts/partials/docs/search.html index bb1fa76..b22bba3 100644 --- a/layouts/partials/docs/search.html +++ b/layouts/partials/docs/search.html @@ -1,6 +1,6 @@ {{ if default true .Site.Params.BookSearch }} <div class="book-search"> - <input type="text" id="book-search-input" placeholder="{{ i18n "Search" }}" aria-label="{{ i18n "Search" }}" maxlength="64" /> + <input type="text" id="book-search-input" placeholder="{{ i18n "Search" }}" aria-label="{{ i18n "Search" }}" maxlength="64" data-hotkeys="s /" /> <div class="book-search-spinner spinner hidden"></div> <ul id="book-search-results"></ul> </div> |