-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautocomplete.js
More file actions
97 lines (82 loc) · 2.97 KB
/
Copy pathautocomplete.js
File metadata and controls
97 lines (82 loc) · 2.97 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import { clickedSearch } from './fetchweather.js'
const ninjaApi = {
key: 'lQkX1TNpDHxVEcCOdkizHg==ijMXifMjNytwpDx5',
baseUrl: "https://api.api-ninjas.com"
}
const userInput = document.getElementById("input-box");
const autocompleteResults = document.getElementById("autocomplete-results");
userInput.addEventListener("input", autoComplete);
/*clear autocomplete elements when somebody clicks in the document:*/
document.addEventListener("click", () => {
closeAllLists(autocompleteResults);
});
function autoComplete() {
if (userInput.value === undefined || userInput.value.length < 1) {
return;
}
let cityArray = [];
let city = userInput.value;
fetch(`${ninjaApi.baseUrl}/v1/city?name=${city}&limit=20`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
'X-Api-Key': ninjaApi.key
}
})
.then((response => {
if (response.ok) {
return response.json();
} else {
throw Error(response.statusText);
}
}))
.then(data => {
if (data.length == 0) {
closeAllLists(autocompleteResults);
return;
}
autocompleteResults.classList.add("open-dropdown");
// console.log('Autocomplete Data:', data);
data.map((item) => {
cityArray.push(`${item.name}, ${item.country}`);
cityArray.sort();
})
// console.log('City Array:', cityArray);
createAutocompleteListElements(cityArray, autocompleteResults, userInput);
})
.catch((error) => {
console.log("Something went wrong.", error);
});
}
function createAutocompleteListElements(data, containerElement, searchInputElement) {
if (!data) {
return;
}
containerElement.innerHTML = "";
data.forEach((item) => {
if (item.substr(0, searchInputElement.value.length).toLowerCase() == searchInputElement.value.toLowerCase()) {
let b = document.createElement("li");
/*makes the matching letters bold*/
b.innerHTML = "<strong>" + item.substr(0, searchInputElement.value.length) + "</strong>";
b.innerHTML += item.substr(searchInputElement.value.length);
// b.innerText = item;
b.addEventListener("click", () => {
searchInputElement.value = item;
clickedSearch();
closeAllLists(containerElement);
});
b.addEventListener('keypress', () => {
if (event.key === "Enter") {
searchInputElement.value = item;
closeAllLists(containerElement);
}
})
containerElement.appendChild(b);
}
})
}
export function closeAllLists(container) {
container.innerHTML = "";
container.classList.remove("open-dropdown");
}