-
Notifications
You must be signed in to change notification settings - Fork 0
/
spott.js
81 lines (64 loc) · 2.2 KB
/
spott.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
69
70
71
72
73
74
75
76
77
78
79
80
function getUrl(city){
let url = `https://spott.p.rapidapi.com/places/autocomplete?type=CITY&q=${city}&limit=5`;
return url
}
function removeAllChildNodes(parent) {
while (parent.firstChild) {
parent.removeChild(parent.firstChild);
}
}
function listRender(data,list,callback){
removeAllChildNodes(list);
for(let item of data){
let text = item['name'] + "," + item['country']['name'];
let listitem = document.createElement("li");
listitem.style.border = "1px solid #ccc";
listitem.style.fontSize = "20px";
listitem.style.padding = "3px"
listitem.addEventListener("mouseover",(e)=>{
e.preventDefault();
listitem.style.cursor = "pointer";
})
listitem.addEventListener("click",()=>{
callback(listitem.textContent);
removeAllChildNodes(list);
});
let node = document.createTextNode(text)
listitem.appendChild(node);
list.appendChild(listitem);
}
}
function autocomplete(idSearch,idspotSearchBox,callback){
const searchDiv = document.getElementById(idSearch);
const spotSearchBox = document.getElementById(idspotSearchBox);
let list = document.createElement("ul");
list.style.listStyleType = "none";
list.style.backgroundColor = "white";
list.style.color = "black";
list.style.padding = "0";
list.style.margin = "0";
list.style.width = searchDiv.style.width;
list.style.borderRadius = "10px"
searchDiv.appendChild(list);
spotSearchBox.addEventListener("input",()=>{
removeAllChildNodes(list);
})
spotSearchBox.addEventListener("keydown",(e)=>{
if(spotSearchBox.value.length <= 1){
removeAllChildNodes(list);
return;
}
fetch(getUrl(spotSearchBox.value), {
"method": "GET",
"headers": {
"x-rapidapi-host": "spott.p.rapidapi.com",
"x-rapidapi-key": SPOTT_API_KEY
}
})
.then(response => response.json())
.then(data => listRender(data,list,callback))
.catch(err => {
console.error(err);
});
})
}