-
Notifications
You must be signed in to change notification settings - Fork 80
/
Copy pathindex.html
64 lines (53 loc) · 1.92 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Type Ahead 👀</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form class="search-form">
<input type="text" class="search" placeholder="City or State">
<ul class="suggestions">
<li>Filter for a city</li>
<li>or a state</li>
</ul>
</form>
<script>
(() => {
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
// Step 1
const cities = [],
searchInput = document.querySelector('.search'),
suggestions = document.querySelector('.suggestions');
// Step 2
fetch(endpoint)
.then(blob => blob.json())
.then(data => cities.push(...data))
// Step 4
const matchInput = (inputString, cities) => cities.filter(({city, state}) => (
city.match(new RegExp(inputString, 'gi')) || state.match(new RegExp(inputString, 'gi'))
));
// Step 6
const numberWithCommas = (x) => x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
// Step 5
const displayMatches = (el) => {
const matchArray = matchInput(el.value, cities)
const suggestionList = matchArray.map((location => {
const regex = new RegExp(el.value, 'gi');
const cityName = location.city.replace(regex, `<span class ="hl">${el.value}</span>`);
const stateName = location.state.replace(regex, `<span class="hl">${el.value}</span>`);
return `
<li>
<span class="name">${cityName}, ${stateName}</span>
<span class="population">${numberWithCommas(location.population)}</span>
</li>`;
})).join('');
suggestions.innerHTML = suggestionList;
}
// Step 3
searchInput.addEventListener('keyup', (e) => displayMatches(searchInput));
})();
</script>
</body>
</html>