Skip to content
This repository was archived by the owner on Feb 13, 2022. It is now read-only.

Commit cfc87d9

Browse files
committed
solution wesbos#6
1 parent e7c7c8f commit cfc87d9

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+
const searchInput = document.querySelector('.search');
22+
const suggestions = document.querySelector('.suggestions');
23+
24+
fetch(endpoint)
25+
.then(blob => blob.json())
26+
.then(data => cities.push(...data));
27+
28+
function findMatches(word, cities) {
29+
return cities.filter(place =>
30+
place.city.toLowerCase().includes(word.toLowerCase()) || place.state.toLowerCase().includes(word.toLowerCase())
31+
);
32+
}
33+
34+
function numberWithCommas(x) {
35+
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
36+
}
37+
38+
function displayMatch() {
39+
const matches = findMatches(this.value, cities);
40+
41+
const html = matches.map(place => {
42+
const regex = new RegExp(this.value, 'gi');
43+
const city = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
44+
const state = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
45+
46+
return `
47+
<li>
48+
<span class="name">${city}, ${state}</span>
49+
<span class="population">${numberWithCommas(place.population)}</span>
50+
</li>
51+
`;
52+
}).join('');
53+
54+
suggestions.innerHTML = html;
55+
}
56+
57+
searchInput.addEventListener('change', displayMatch);
58+
searchInput.addEventListener('keyup', displayMatch);
59+
2060
</script>
2161
</body>
2262
</html>

0 commit comments

Comments
 (0)