File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11<!DOCTYPE html>
22< 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- < script >
18- const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json' ;
19-
20- </ script >
3+ < head >
4+ < meta charset ="UTF-8 ">
5+ < title > Type Ahead 👀</ title >
6+ < link rel ="stylesheet " href ="style.css ">
7+ </ head >
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 src ="index.js "> </ script >
2117 </ body >
2218</ html >
Original file line number Diff line number Diff line change 1+ class Suggester {
2+ constructor ( ) {
3+ this . cities = [ ] ;
4+ const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json' ;
5+ fetch ( endpoint )
6+ . then ( resp => resp . json ( ) )
7+ . then ( data => this . cities . push ( ...data ) ) ;
8+ }
9+
10+ listMatches ( wordToMatch ) {
11+ const regex = new RegExp ( wordToMatch , 'gi' ) ;
12+ const html = this . cities
13+ . filter ( place => regex . test ( place . city ) || regex . test ( place . state ) )
14+ . map ( place => {
15+ const highlight = `<span class="hl">${ wordToMatch } </span>` ;
16+ const cityName = place . city . replace ( regex , highlight ) ;
17+ const stateName = place . state . replace ( regex , highlight ) ;
18+ return `<li><span class="name">${ cityName } , ${ stateName } </span></li>` ;
19+ } )
20+ . join ( "\n" ) ;
21+ return html ;
22+ }
23+ }
24+
25+ const searchInput = document . querySelector ( 'input.search' ) ;
26+ const suggestions = document . querySelector ( 'ul.suggestions' ) ;
27+ const suggester = new Suggester ( ) ;
28+ const displayMatches = ( ) => suggestions . innerHTML = suggester . listMatches ( searchInput . value ) ;
29+ searchInput . addEventListener ( 'change' , displayMatches ) ;
30+ searchInput . addEventListener ( 'keyup' , displayMatches ) ;
You can’t perform that action at this time.
0 commit comments