Skip to content

Commit 2d29bc0

Browse files
committed
Finish part 6
1 parent 72446a8 commit 2d29bc0

1 file changed

Lines changed: 46 additions & 5 deletions

File tree

06 - Type Ahead/index-START.html

Lines changed: 46 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
<!DOCTYPE html>
22
<html lang="en">
3+
34
<head>
45
<meta charset="UTF-8">
56
<title>Type Ahead 👀</title>
67
<link rel="stylesheet" href="style.css">
78
</head>
9+
810
<body>
911

1012
<form class="search-form">
@@ -14,9 +16,48 @@
1416
<li>or a state</li>
1517
</ul>
1618
</form>
17-
<script>
18-
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
19+
<script>
20+
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
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.city.match(regex)
31+
})
32+
}
33+
34+
function numberWithCommas(x) {
35+
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
36+
}
37+
38+
const searchInput = document.querySelector('.search');
39+
const suggestions = document.querySelector('.suggestions');
40+
41+
searchInput.addEventListener('change', displayMatches);
42+
searchInput.addEventListener('keyup', displayMatches);
43+
44+
function displayMatches() {
45+
const matchArray = findMatches(this.value, cities);
46+
const html = matchArray.map(place => {
47+
const regex = new RegExp(this.value, 'gi');
48+
const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
49+
const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
50+
return `
51+
<li>
52+
<span class="name">${ cityName }, ${ stateName }</span>
53+
<span class="population">${ numberWithCommas(place.population) }</span>
54+
</li>
55+
`
56+
}).join('');
57+
suggestions.innerHTML = html;
58+
}
59+
60+
</script>
61+
</body>
1962

20-
</script>
21-
</body>
22-
</html>
63+
</html>

0 commit comments

Comments
 (0)