Skip to content

Commit 938c415

Browse files
committed
typeahead complete
1 parent ef9e560 commit 938c415

File tree

2 files changed

+65
-22
lines changed

2 files changed

+65
-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: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
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+
19+
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
20+
21+
const cities = [];
22+
23+
fetch(endpoint).then(blob => blob.json())
24+
.then(data => cities.push(...data));
25+
26+
function findMatches(wordToMatch, cities) {
27+
return cities.filter(place => {
28+
const regex = new RegExp(wordToMatch, 'gi')
29+
30+
return place.city.match(regex) || place.state.match(regex);
31+
})
32+
}
33+
34+
function numbersWithCommas(x) {
35+
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
36+
}
37+
38+
function displayMatches() {
39+
const matchArray = findMatches(this.value, cities);
40+
const regex = new RegExp(this.value, 'gi');
41+
42+
const html = matchArray.map(place => {
43+
const cityName = place.city.replace(regex, `<span class=h1">${this.value}</span>`);
44+
const stateName = place.state.replace(regex, `<span class=h1">${this.value}</span>`);
45+
return `
46+
<li>
47+
<span class="name">${cityName}, ${stateName}</span>
48+
<span class="population">${numbersWithCommas(place.population)}</span>
49+
</li>
50+
`;
51+
}).join('');
52+
53+
suggestions.innerHTML = html;
54+
}
55+
56+
const searchInput = document.querySelector('.search');
57+
const suggestions = document.querySelector('.suggestions');
58+
59+
searchInput.addEventListener('change', displayMatches)
60+
searchInput.addEventListener('keyup', displayMatches)
61+
62+
63+
</script>
64+
</body>
65+
</html>

0 commit comments

Comments
 (0)