Skip to content

Commit c7f5cac

Browse files
committed
finished challenge wesbos#6
1 parent 12649ce commit c7f5cac

File tree

2 files changed

+50
-2
lines changed

2 files changed

+50
-2
lines changed

06 - Type Ahead/index-START.html

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@
1414
<li>or a state</li>
1515
</ul>
1616
</form>
17-
<script>
18-
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
17+
<script type="text/javascript" src="script.js">
18+
1919

2020
</script>
2121
</body>

06 - Type Ahead/script.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
2+
3+
const cities = [];
4+
5+
//fetch will return a promise
6+
fetch(endpoint)
7+
// .then(blob => console.log(blob))
8+
//data that comes back from fetch, it doesn't know what it's coming back yet; blob needs to be converted from raw data into JSON
9+
.then(blob => blob.json())
10+
.then(data => cities.push(...data))
11+
12+
function findMatches(wordToMatch, cities) {
13+
return cities.filter(place => {
14+
//here we need to figure out if city/state matches what was searched
15+
const regex = new RegExp(wordToMatch, 'gi');
16+
return place.city.match(regex) || place.state.match(regex)
17+
})
18+
}
19+
20+
function numberWithCommas(x) {
21+
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
22+
}
23+
24+
//whenever someone changes the values
25+
function displayMatches() {
26+
// console.log(this.value)
27+
const matchArray = findMatches(this.value, cities);
28+
// console.log(matchArray)
29+
const html = matchArray.map(place => {
30+
//find whatever is in regex
31+
const regex = new RegExp(this.value, 'gi')
32+
const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`)
33+
const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`)
34+
return `
35+
<li>
36+
<span class="name">${cityName}, ${stateName}</span>
37+
<span class="population">${numberWithCommas(place.population)}</span>
38+
</li>
39+
`;
40+
}).join('');
41+
suggestions.innerHTML = html;
42+
}
43+
44+
const searchInput = document.querySelector('.search');
45+
const suggestions = document.querySelector('.suggestions');
46+
47+
searchInput.addEventListener('change', displayMatches)
48+
searchInput.addEventListener('keyup', displayMatches)

0 commit comments

Comments
 (0)