Skip to content

Commit 703ada0

Browse files
committed
Finished wesbos#6
1 parent b2a0bae commit 703ada0

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

06 - Type Ahead/index-START.html

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,46 @@
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+
// console.log(cities);
27+
28+
function findCities(enteredText, cities) {
29+
return cities.filter(place => {
30+
const regex = new RegExp(enteredText, 'gi');
31+
return place.city.match(regex) || place.state.match(regex);
32+
});
33+
}
34+
35+
function numberWithCommas(x) {
36+
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
37+
}
38+
39+
function displayCities() {
40+
const matchArray = findCities(this.value, cities);
41+
const html = matchArray.map(place => {
42+
const regex = new RegExp(this.value, 'gi');
43+
const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
44+
const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
45+
return `<li>
46+
<span class="name">${cityName}, ${stateName}</span>
47+
<span class="population">${numberWithCommas(place.population)}</span>
48+
</li>`;
49+
}).join('');
50+
suggestions.innerHTML = html;
51+
}
52+
53+
const searchInput = document.querySelector('.search');
54+
const suggestions = document.querySelector('.suggestions');
55+
56+
searchInput.addEventListener('change', displayCities);
57+
searchInput.addEventListener('keyup', displayCities);
58+
59+
2060
</script>
2161
</body>
2262
</html>

0 commit comments

Comments
 (0)