Skip to content

Commit 80ef3e8

Browse files
lección wesbos#6
1 parent 0f2b35c commit 80ef3e8

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

06 - Type Ahead/index-START.html

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

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

0 commit comments

Comments
 (0)