Visitar URL original
finished JS Day #6 · kdipaolo/JavaScript30@68722ec · GitHub
Skip to content

Commit 68722ec

Browse files
committed
finished JS Day wesbos#6
1 parent ef27fd6 commit 68722ec

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

‎06 - Type Ahead/index-START.html‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,39 @@
1616
</form>
1717
<script>
1818
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
19+
const cities = [];
20+
const promise = fetch(endpoint)
21+
.then(rawResponse => rawResponse.json())
22+
.then(data => cities.push(...data));
23+
24+
const search = document.querySelector('.search');
25+
const suggestions = document.querySelector('.suggestions');
26+
27+
function findMatches(word){
28+
return cities.filter(place => {
29+
const regex = new RegExp(word, 'gi')
30+
return place.city.match(regex) || place.state.match(regex)
31+
})
32+
}
33+
34+
function displayMatches(){
35+
const newMatches = findMatches(this.value);
36+
const html = newMatches.map(place => {
37+
const regex = new RegExp(this.value, 'gi');
38+
const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`)
39+
const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`)
40+
return `
41+
<li>
42+
<span class="name">${cityName}, ${stateName}</span>
43+
<span class="population">${place.population}</span>
44+
</li>`
45+
}).join('')
46+
suggestions.innerHTML = html;
47+
}
48+
49+
search.addEventListener('keyup', displayMatches)
50+
search.addEventListener('change', displayMatches)
51+
1952

2053
</script>
2154
</body>

0 commit comments

Comments
 (0)