File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree 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+ let cities = [ ] ;
21+
22+ async function getData ( ) {
23+ const response = await fetch ( endpoint ) ;
24+ cities = await response . json ( ) ;
25+ }
26+
27+ function numberWithCommas ( x ) {
28+ return x . toString ( ) . replace ( / \B (? = ( \d { 3 } ) + (? ! \d ) ) / g, ',' ) ;
29+ }
30+
31+ function handleSearch ( ) {
32+ console . log ( 'hey' , this . value ) ;
33+ const filtered = cities . filter ( c => c . city . toLowerCase ( ) . includes ( this . value ) || c . state . toLowerCase ( ) . includes ( this . value ) )
34+ console . log ( filtered ) ;
35+
36+ const ulElement = document . querySelector ( '.suggestions' ) ;
37+ const html = filtered . map ( place => {
38+ const regex = new RegExp ( this . value , 'gi' ) ;
39+ const cityName = place . city . replace ( regex , `<span class="hl">${ this . value } </span>` ) ;
40+ const stateName = place . state . replace ( regex , `<span class="hl">${ this . value } </span>` ) ;
41+ return `
42+ <li>
43+ <span class="name">${ cityName } , ${ stateName } </span>
44+ <span class="population">${ numberWithCommas ( place . population ) } </span>
45+ </li>
46+ ` ;
47+ } ) . join ( '' ) ;
48+
49+ ulElement . innerHTML = html ;
50+ }
51+
52+ async function start ( ) {
53+ await getData ( ) ;
54+
55+ const input = document . querySelector ( '.search' ) ;
56+ input . addEventListener ( 'keyup' , handleSearch ) ;
57+ }
58+
59+ start ( ) ;
60+
2061</ script >
2162</ body >
2263</ html >
You can’t perform that action at this time.
0 commit comments