Skip to content

Commit a13ee9b

Browse files
committed
1 parent c635af0 commit a13ee9b

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

06 - Type Ahead/index.html

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<title>Type Ahead 👀</title>
6+
<link rel="stylesheet" href="style.css">
7+
<script src="http://localhost:35729/livereload.js"></script>
8+
</head>
9+
<body>
10+
11+
<form class="search-form">
12+
<input type="text" class="search" placeholder="City or State">
13+
<ul class="suggestions">
14+
<li>Filter for a city</li>
15+
<li>or a state</li>
16+
</ul>
17+
</form>
18+
<script>
19+
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
20+
// fetch cities data
21+
const cities = [];
22+
fetch(endpoint)
23+
.then(res => res.json())
24+
.then(data => cities.push(...data));
25+
26+
function findMatches(word, cities) {
27+
return cities.filter(place => {
28+
const rg = new RegExp(word, 'gi');
29+
return place.city.match(rg) || place.state.match(rg);
30+
})
31+
}
32+
33+
function displayMatches() {
34+
const searchTerm = this.value;
35+
const matches = findMatches(searchTerm, cities);
36+
const rg = new RegExp(searchTerm, 'gi');
37+
const html = matches.map(elm => `
38+
<li>
39+
<span class="name">${elm.city.replace(rg, `<span class="hl">${searchTerm}</span>`)}, ${elm.state.replace(rg, `<span class="hl">${searchTerm}</span>`)}</span>
40+
<span class="population">${elm.population}</span>
41+
</li>
42+
`).join('');
43+
44+
suggestions.innerHTML = html;
45+
}
46+
47+
const searchInput = document.querySelector('.search');
48+
const suggestions = document.querySelector('.suggestions');
49+
50+
searchInput.addEventListener('change', displayMatches);
51+
searchInput.addEventListener('keyup', displayMatches);
52+
</script>
53+
</body>
54+
</html>

0 commit comments

Comments
 (0)