Skip to content

Commit 2c58d7e

Browse files
committed
Finished type ahead script
1 parent 93ebac5 commit 2c58d7e

File tree

4 files changed

+64
-22
lines changed

4 files changed

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

06 - Type Ahead/index-START.html

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

0 commit comments

Comments
 (0)