Skip to content

Commit 83e4c41

Browse files
committed
Lesson 06
1 parent 6877f2e commit 83e4c41

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

06 - Type Ahead/index.html

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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+
</head>
8+
<body>
9+
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+
20+
const cities = [];
21+
22+
fetch(endpoint)
23+
.then(blob => blob.json())
24+
.then(data => cities.push(...data));
25+
26+
function findMatches(word, cities){
27+
const reg = new RegExp(word, 'gi');
28+
return cities.filter(place => {
29+
return place.city.match(reg) || place.state.match(reg);
30+
}
31+
)}
32+
33+
function displayMatches(){
34+
if(this.value.length < 3) return;
35+
const matches = findMatches(this.value, cities);
36+
const reg = new RegExp(this.value, 'gi');
37+
38+
const html = matches.map(place => {
39+
const cityName = place.city.replace(
40+
reg, `<span class="hl">${this.value}</span>`);
41+
const stateName = place.state.replace(
42+
reg, `<span class="hl">${this.value}</span>`);
43+
return `
44+
<li>
45+
<span class="name">${cityName}, ${stateName}</span>
46+
<span class="population">${place.population}</span>
47+
</li>
48+
`;
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);
59+
60+
</script>
61+
</body>
62+
</html>

0 commit comments

Comments
 (0)