Skip to content

Commit f68d7aa

Browse files
Adds Day 6 Finished Code
1 parent 4e2cdb8 commit f68d7aa

1 file changed

Lines changed: 43 additions & 10 deletions

File tree

06 - Type Ahead/index-START.html

Lines changed: 43 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,50 @@
66
<link rel="stylesheet" href="style.css">
77
</head>
88
<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>
17+
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
918

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+
const cities = [];
1920

20-
</script>
21+
fetch(endpoint)
22+
.then(blob => blob.json())
23+
.then(data => cities.push(...data));
24+
25+
function findMatches(wordToMatch, cities) {
26+
return cities.filter(place => {
27+
const regex = new RegExp(wordToMatch, 'gi');
28+
return place.city.match(regex) || place.state.match(regex);
29+
});
30+
}
31+
32+
function displayMatches() {
33+
const matchArray = findMatches(this.value, cities);
34+
const html = matchArray.map(place => {
35+
const regex = new RegExp(this.value, 'gi');
36+
const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
37+
const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
38+
return `
39+
<li>
40+
<span class="name">${cityName}, ${stateName}</span>
41+
<span class="population">${place.population}</span>
42+
</li>
43+
`;
44+
}).join('');
45+
suggestions.innerHTML = html;
46+
}
47+
48+
const searchInput = document.querySelector('.search');
49+
const suggestions = document.querySelector('.suggestions');
50+
51+
searchInput.addEventListener('change', displayMatches);
52+
searchInput.addEventListener('keyup', displayMatches);
53+
</script>
2154
</body>
2255
</html>

0 commit comments

Comments
 (0)