-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
68 lines (62 loc) · 2.16 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
'use strict';
/* global Event */
module.exports = function (settings) {
if (!typeof settings === 'object' || !settings.input || !settings.suggestions) {
throw new Error('Missing required settings.');
}
var highlightedClass = settings.highlightedClass || 'highlighted';
var highlightedClassSelector = '.' + highlightedClass;
var input = settings.input;
var suggestions = settings.suggestions;
var KEY_UP = 38;
var KEY_DOWN = 40;
var KEY_TAB = 9;
var KEY_ENTER = 13;
input.addEventListener('keydown', function (e) {
if (suggestions.childNodes.length === 0) {
// No suggestions available
return;
}
var which = e.which || e.keyCode;
switch (which) {
case KEY_UP:
e.preventDefault();
move('up', suggestions, highlightedClass, highlightedClassSelector);
break;
case KEY_DOWN:
e.preventDefault();
move('down', suggestions, highlightedClass, highlightedClassSelector);
break;
case KEY_TAB:
onTab(e, suggestions);
break;
case KEY_ENTER:
onEnter(e, suggestions);
break;
default:
break;
}
});
function move(direction, suggestions, highlightedClass, highlightedClassSelector) {
var lastIndex = suggestions.childNodes.length - 1;
var currentSuggestion = suggestions.querySelector(highlightedClassSelector);
var nextSuggestion;
if (direction === 'up') {
currentSuggestion = currentSuggestion ? currentSuggestion : suggestions.childNodes[0];
nextSuggestion = currentSuggestion.previousSibling || suggestions.childNodes[lastIndex];
} else {
currentSuggestion = currentSuggestion ? currentSuggestion : suggestions.childNodes[lastIndex];
nextSuggestion = currentSuggestion.nextSibling || suggestions.childNodes[0];
}
currentSuggestion.classList.remove(highlightedClass);
nextSuggestion.classList.add(highlightedClass);
}
function onTab(e, suggestions) {
e.preventDefault();
e.target.value = suggestions.querySelector(highlightedClassSelector).innerText;
e.target.dispatchEvent(new Event('input'));
}
function onEnter(e, suggestions) {
onTab(e, suggestions);
}
};