forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path18_2_autocompletion.html
More file actions
31 lines (27 loc) · 902 Bytes
/
18_2_autocompletion.html
File metadata and controls
31 lines (27 loc) · 902 Bytes
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
<!doctype html>
<input type="text" id="field">
<div id="suggestions" style="cursor: pointer"></div>
<script>
// Builds up an array with global variable names, like
// 'alert', 'document', and 'scrollTo'
var terms = [];
for (var name in window)
terms.push(name);
var textfield = document.querySelector("#field");
var suggestions = document.querySelector("#suggestions");
textfield.addEventListener("input", function() {
var matching = terms.filter(function(term) {
return term.indexOf(textfield.value) == 0;
});
suggestions.textContent = "";
matching.slice(0, 20).forEach(function(term) {
var node = document.createElement("div");
node.textContent = term;
node.addEventListener("click", function() {
textfield.value = term;
suggestions.textContent = "";
});
suggestions.appendChild(node);
});
});
</script>