Skip to content

Commit b0bc154

Browse files
committed
Finish 6
1 parent 614eb65 commit b0bc154

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

06 - Type Ahead/index-START.html

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

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

0 commit comments

Comments
 (0)