Skip to content

Commit 5b87f05

Browse files
committed
finish 6
1 parent 622d7e3 commit 5b87f05

File tree

2 files changed

+55
-22
lines changed

2 files changed

+55
-22
lines changed

06 - Type Ahead/index-START.html

Lines changed: 0 additions & 22 deletions
This file was deleted.

06 - Type Ahead/index.html

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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+
let cities = [];
20+
21+
fetch(endpoint)
22+
.then(blob => blob.json())
23+
.then(data => cities.push(...data));
24+
25+
function findMatches(wordToMatch, citiesArry) {
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+
46+
suggestions.innerHTML = html;
47+
}
48+
49+
const searchInput = document.querySelector('.search');
50+
const suggestions = document.querySelector('.suggestions');
51+
52+
searchInput.addEventListener('keyup', displayMatches);
53+
</script>
54+
</body>
55+
</html>

0 commit comments

Comments
 (0)