Skip to content

Commit 6a9fe12

Browse files
committed
wesbos#6 - Type Ahead
1 parent ea80158 commit 6a9fe12

File tree

1 file changed

+48
-5
lines changed

1 file changed

+48
-5
lines changed

06 - Type Ahead/index-START.html

Lines changed: 48 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,65 @@
11
<!DOCTYPE html>
22
<html lang="en">
3+
34
<head>
45
<meta charset="UTF-8">
56
<title>Type Ahead 👀</title>
67
<link rel="stylesheet" href="style.css">
78
</head>
9+
810
<body>
911

1012
<form class="search-form">
11-
<input type="text" class="search" placeholder="City or State">
13+
<input type="text" class="search" placeholder="City or State" autofocus>
1214
<ul class="suggestions">
1315
<li>Filter for a city</li>
1416
<li>or a state</li>
1517
</ul>
1618
</form>
17-
<script>
18-
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
19+
<script>
20+
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
21+
22+
const cities = [];
23+
let yourLatitude = 0;
24+
let yourLongitude = 0;
25+
26+
fetch(endpoint)
27+
.then(blob => blob.json())
28+
.then(data => cities.push(...data));
29+
30+
function findMatches(wordToMatch, cities) {
31+
return cities.filter(place => {
32+
const regex = new RegExp(wordToMatch, 'gi');
33+
return place.city.match(regex) || place.state.match(regex);
34+
});
35+
}
1936

20-
</script>
37+
function numberWithCommas(x) {
38+
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
39+
}
40+
41+
function displayMatches() {
42+
const matchArray = findMatches(this.value, cities);
43+
const html = matchArray.map(place => {
44+
const regex = new RegExp(this.value, 'gi');
45+
let cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
46+
let stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
47+
return `
48+
<li>
49+
<span class="name">${cityName}, ${stateName}</span>
50+
<span class="population">${numberWithCommas(place.population)}</span>
51+
</li>
52+
`;
53+
}).join('');
54+
suggestions.innerHTML = html;
55+
}
56+
57+
const searchInput = document.querySelector('.search');
58+
const suggestions = document.querySelector('.suggestions');
59+
60+
searchInput.addEventListener('change', displayMatches);
61+
searchInput.addEventListener('keyup', displayMatches);
62+
</script>
2163
</body>
22-
</html>
64+
65+
</html>

0 commit comments

Comments
 (0)