File tree 2 files changed +59
-0
lines changed
2 files changed +59
-0
lines changed Original file line number Diff line number Diff line change
1
+ <!DOCTYPE html>
2
+ < html lang ="en ">
3
+ < head >
4
+ < meta charset ="UTF-8 ">
5
+ < title > Type Ahead 👀</ title >
6
+ < link rel ="stylesheet " href ="style.css ">
7
+ </ head >
8
+ < body >
9
+
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
+
18
+ < script src ="script.js " charset ="utf-8 "> </ script >
19
+
20
+ </ body >
21
+ </ html >
Original file line number Diff line number Diff line change
1
+ 'use strict' ;
2
+
3
+ const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json' ;
4
+
5
+ let cities = [ ] ;
6
+
7
+ fetch ( endpoint )
8
+ . then ( blob => blob . json ( ) )
9
+ . then ( data => cities = data ) ;
10
+
11
+ function findMatches ( wordToMatch , cities ) {
12
+ return cities . filter ( ( place ) => {
13
+ const regexp = new RegExp ( wordToMatch , 'gi' ) ;
14
+ return place . city . match ( regexp ) || place . state . match ( regexp ) ;
15
+ } ) ;
16
+ }
17
+
18
+ function numberWithCommas ( x ) {
19
+ return x . toString ( ) . replace ( / \B (? = ( \d { 3 } ) + (? ! \d ) ) / g, ',' ) ;
20
+ }
21
+
22
+ function displayMatcher ( ) {
23
+ const matches = findMatches ( this . value , cities ) ;
24
+ const regexp = new RegExp ( this . value , 'gi' ) ;
25
+ const html = matches . map ( place => {
26
+ const cityName = place . city . replace ( regexp , `<span class='hl'>${ this . value } </span>` ) ;
27
+ const stateName = place . state . replace ( regexp , `<span class='hl'>${ this . value } </span>` ) ;
28
+ return `
29
+ <li>
30
+ <span class="name">${ cityName } , ${ stateName } </span>
31
+ <span class="population">${ numberWithCommas ( place . population ) } </span>
32
+ </li>
33
+ ` ;
34
+ } ) . join ( '' ) ;
35
+ document . querySelector ( '.suggestions' ) . innerHTML = html ;
36
+ }
37
+
38
+ document . querySelector ( '.search' ) . addEventListener ( 'keyup' , displayMatcher ) ;
You can’t perform that action at this time.
0 commit comments