-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
75 lines (58 loc) · 1.89 KB
/
Copy pathscript.js
File metadata and controls
75 lines (58 loc) · 1.89 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
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
let places, matchedPlaces;
document.addEventListener("DOMContentLoaded", async () => {
places = await fetchData();
const suggestions = document.querySelector(".suggestions");
// listen for change in input
document.querySelector(".search-bar")
.addEventListener("input",
e => handleChange(e.target, suggestions)
);
});
async function fetchData() {
try {
return await fetch(endpoint)
.then(res => res.json())
.then(obj => obj);
}
catch(err) {
console.error(err);
alert("An unknown error occurred! Please open the console for more info.");
}
}
function handleChange(searchBar, suggestions) {
if(searchBar.value) {
const matchedPlaces = findMatches(searchBar.value);
// create <li> nodes for matchedPlaces
const listItems = matchedPlaces.map(place =>
getListItemHTML(place, searchBar.value)
);
suggestions.innerHTML = listItems.join("");
return;
}
// if searchBar is empty
suggestions.innerHTML = "";
}
function findMatches(input) {
return (
places.filter(place => {
const regExp = new RegExp(input, "gi");
// find either city or state should match
return place.city.match(regExp) || place.state.match(regExp);
})
)}
function getListItemHTML(place, input) {
// for highlighting the substring that matches the input
const regExp = new RegExp(input, "gi");
const spanHighlight = `<span class="highlight">${input}</span>`;
// replace substring with highlighted one
const city = place.city.replace(regExp, spanHighlight);
const state = place.state.replace(regExp, spanHighlight);
return `<li>
<span>${city}, ${state}</span>
<span class="population">${formatPopulation(place.population)}</span>
</li>`;
}
function formatPopulation(number) {
return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}