#134, Focus search field by pressing s or / (#135)

* #134, Focus search field by pressing s or /
* #134, Refactoring away an array loop using indexOf
This commit is contained in:
Daniel Forssten 2020-01-19 21:57:53 +01:00 committed by Alex Shpak
parent 4b641b0f9a
commit 7e2af86777
2 changed files with 24 additions and 1 deletions

View file

@ -10,6 +10,29 @@
input.addEventListener('focus', init); input.addEventListener('focus', init);
input.addEventListener('keyup', search); 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() { function init() {
input.removeEventListener('focus', init); // init once input.removeEventListener('focus', init); // init once
input.required = true; input.required = true;

View file

@ -1,6 +1,6 @@
{{ if default true .Site.Params.BookSearch }} {{ if default true .Site.Params.BookSearch }}
<div class="book-search"> <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> <div class="book-search-spinner spinner hidden"></div>
<ul id="book-search-results"></ul> <ul id="book-search-results"></ul>
</div> </div>