Skip to content

Commit 2b071c6

Browse files
author
Yuri Brunetto
committed
complete wesbos#6
1 parent 3caec4b commit 2b071c6

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

06 - Type Ahead/index-START.html

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,47 @@
1515
</ul>
1616
</form>
1717
<script>
18-
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
18+
19+
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
20+
21+
const cities = []
22+
23+
fetch(endpoint)
24+
.then(blob => blob.json())
25+
.then(data => cities.push(...data))
26+
27+
function findMatches(wordToMatch, cities) {
28+
return cities.filter(place => {
29+
const regex = new RegExp(wordToMatch, 'gi')
30+
return place.city.match(regex) || place.state.match(regex)
31+
})
32+
}
33+
34+
function numberWithCommas(x) {
35+
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
36+
}
37+
38+
function displayMatches() {
39+
const matchArray = findMatches(this.value, cities)
40+
const html = matchArray.map(place => {
41+
const regex = new RegExp(this.value, 'gi')
42+
const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`)
43+
const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`)
44+
45+
return `<li>
46+
<span class="name">${cityName}, ${stateName}</span>
47+
<span class="population">${numberWithCommas(place.population)}</span>
48+
</li>`
49+
}).join('')
50+
51+
suggestions.innerHTML = html
52+
}
53+
54+
const searchInput = document.querySelector('.search')
55+
const suggestions = document.querySelector('.suggestions')
56+
57+
searchInput.addEventListener('change', displayMatches)
58+
searchInput.addEventListener('keyup', displayMatches)
1959

2060
</script>
2161
</body>

06 - Type Ahead/style.css

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55
font-size: 20px;
66
font-weight: 200;
77
}
8+
* {
9+
-webkit-font-smoothing: antialiased;
10+
}
811
*, *:before, *:after {
912
box-sizing: inherit;
1013
}

0 commit comments

Comments
 (0)