File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Open diff view settings
Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Open diff view settings
Original file line number Diff line number Diff line change 1717< script >
1818const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json' ;
1919
20+ const cities = [ ] ;
21+
22+ fetch ( endpoint ) . 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+
2054</ script >
2155 </ body >
2256</ html >
You can’t perform that action at this time.
0 commit comments