|
14 | 14 | <li>or a state</li>
|
15 | 15 | </ul>
|
16 | 16 | </form>
|
17 |
| -<script> |
18 |
| -const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json'; |
| 17 | + <script> |
| 18 | + const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json'; |
19 | 19 |
|
20 |
| -</script> |
21 |
| - </body> |
| 20 | + const cities = []; |
| 21 | + fetch(endpoint) |
| 22 | + .then(res => res.json()) |
| 23 | + .then(data => cities.push(...data)); |
| 24 | + |
| 25 | + function findMatches(wordToMatch, cities) { |
| 26 | + const regex = new RegExp(wordToMatch, 'gi'); |
| 27 | + return cities.filter(p => p.city.match(regex) || p.state.match(regex)); |
| 28 | + } |
| 29 | + |
| 30 | + function numberWithCommas(number){ |
| 31 | + return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); |
| 32 | + } |
| 33 | + |
| 34 | + function displayMatches(){ |
| 35 | + const matches = findMatches(this.value, cities); |
| 36 | + const html = matches.map(p => { |
| 37 | + const regex = new RegExp(this.value, 'gi'); |
| 38 | + const city = p.city.replace(regex, `<span class="hl">${this.value}</span>`); |
| 39 | + const state = p.state.replace(regex, `<span class="hl">${this.value}</span>`); |
| 40 | + const population = numberWithCommas(p.population); |
| 41 | + |
| 42 | + return ` |
| 43 | + <li> |
| 44 | + <span class="name">${city}, ${state}</span> |
| 45 | + <span class="population">${population}</span> |
| 46 | + </li> |
| 47 | + `; |
| 48 | + }).join(''); |
| 49 | + |
| 50 | + suggestions.innerHTML = html; |
| 51 | + } |
| 52 | + |
| 53 | + const suggestions = document.querySelector('.suggestions'); |
| 54 | + const searchInput = document.querySelector('.search'); |
| 55 | + searchInput.addEventListener('change', displayMatches); |
| 56 | + searchInput.addEventListener('keyup', displayMatches); |
| 57 | + </script> |
| 58 | +</body> |
22 | 59 | </html>
|
0 commit comments