Skip to content

Commit 7bd13c8

Browse files
committed
Finished day wesbos#6: Type Agead
1 parent b972a47 commit 7bd13c8

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

06 - Type Ahead/index-START.html

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,45 @@
1717
<script>
1818
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
1919

20+
const cities = [];
21+
22+
fetch(endpoint)
23+
.then(blob => blob.json())
24+
.then(data => cities.push(...data));
25+
26+
function findMatches(query, cities) {
27+
return cities.filter(place => {
28+
const regex = RegExp(query, 'gi');
29+
return place.city.match(regex) || place.state.match(regex);
30+
});
31+
}
32+
33+
function numberWithCommas(x) {
34+
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
35+
}
36+
37+
function displayMatches() {
38+
const matchArray = findMatches(this.value, cities);
39+
const regex = new RegExp(this.value, 'gi');
40+
const html = matchArray.map(place => {
41+
const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
42+
const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
43+
return `
44+
<li>
45+
<span class="name">${cityName}, ${stateName}</span>
46+
<span class="population">${numberWithCommas(place.population)}</span>
47+
</li>
48+
`;
49+
}).join('');
50+
list.innerHTML = html;
51+
}
52+
53+
const input = document.querySelector('.search');
54+
const list = document.querySelector('.suggestions');
55+
56+
input.addEventListener('change', displayMatches);
57+
input.addEventListener('keyup', displayMatches);
58+
2059
</script>
2160
</body>
2261
</html>

0 commit comments

Comments
 (0)