From 7e2af86777bee9cd9483152f9f8be79c98c43fb9 Mon Sep 17 00:00:00 2001 From: Daniel Forssten Date: Sun, 19 Jan 2020 21:57:53 +0100 Subject: #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 --- assets/search.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'assets/search.js') 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; -- cgit v1.2.3