|
6 | 6 | <link rel="stylesheet" href="style.css"> |
7 | 7 | </head> |
8 | 8 | <body> |
| 9 | + <form class="search-form"> |
| 10 | + <input type="text" class="search" placeholder="City or State"> |
| 11 | + <ul class="suggestions"> |
| 12 | + <li>Filter for a city</li> |
| 13 | + <li>or a state</li> |
| 14 | + </ul> |
| 15 | + </form> |
| 16 | + <script> |
| 17 | + const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json'; |
9 | 18 |
|
10 | | - <form class="search-form"> |
11 | | - <input type="text" class="search" placeholder="City or State"> |
12 | | - <ul class="suggestions"> |
13 | | - <li>Filter for a city</li> |
14 | | - <li>or a state</li> |
15 | | - </ul> |
16 | | - </form> |
17 | | -<script> |
18 | | -const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json'; |
| 19 | + const cities = []; |
19 | 20 |
|
20 | | -</script> |
| 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 displayMatches() { |
| 33 | + const matchArray = findMatches(this.value, cities); |
| 34 | + const html = matchArray.map(place => { |
| 35 | + const regex = new RegExp(this.value, 'gi'); |
| 36 | + const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`); |
| 37 | + const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`); |
| 38 | + return ` |
| 39 | + <li> |
| 40 | + <span class="name">${cityName}, ${stateName}</span> |
| 41 | + <span class="population">${place.population}</span> |
| 42 | + </li> |
| 43 | + `; |
| 44 | + }).join(''); |
| 45 | + suggestions.innerHTML = html; |
| 46 | + } |
| 47 | + |
| 48 | + const searchInput = document.querySelector('.search'); |
| 49 | + const suggestions = document.querySelector('.suggestions'); |
| 50 | + |
| 51 | + searchInput.addEventListener('change', displayMatches); |
| 52 | + searchInput.addEventListener('keyup', displayMatches); |
| 53 | + </script> |
21 | 54 | </body> |
22 | 55 | </html> |
0 commit comments