Skip to content

Commit 75b5b78

Browse files
committed
Implement type ahead functionality
1 parent ca8cb25 commit 75b5b78

2 files changed

Lines changed: 71 additions & 0 deletions

File tree

06 - Type Ahead/.jshintrc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{ "esnext": true }

06 - Type Ahead/index.html

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
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+
const cities = [];
20+
// using the new fetch API.. with promises
21+
fetch(endpoint)
22+
.then(blob => blob.json())
23+
// spread the data into the push method to populate the cities array.
24+
.then(data => cities.push(...data));
25+
// .then(data => console.log(data));
26+
27+
function findMatches(wordToMatch, cities) {
28+
return cities.filter(place => {
29+
// figure out if the city or state matches what was searched
30+
const regex = new RegExp(wordToMatch, 'gi'); // global, insensitive
31+
return place.city.match(regex) || place.state.match(regex);
32+
});
33+
}
34+
35+
function numberWithCommas(x) {
36+
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
37+
}
38+
39+
function displayMatches() {
40+
// console.log(this.value);
41+
const matchArray = findMatches(this.value, cities);
42+
console.log(matchArray);
43+
const html = matchArray.map(place => {
44+
45+
// create the highlight
46+
const regex = new RegExp(this.value, 'gi');
47+
const cityName = place.city.replace(regex,
48+
`<span class="hl">${this.value}</span>`);
49+
const stateName = place.state.replace(regex,
50+
`<span class="hl">${this.value}</span>`);
51+
52+
return `
53+
<li>
54+
<span class="name">${cityName}, ${stateName}</span>
55+
<span class="population">${numberWithCommas(place.population)}</span>
56+
</li>
57+
`;
58+
}).join(''); // convert the array to a string.
59+
suggestions.innerHTML = html;
60+
}
61+
62+
const searchInput = document.querySelector('.search');
63+
const suggestions = document.querySelector('.suggestions');
64+
65+
searchInput.addEventListener('change', displayMatches);
66+
searchInput.addEventListener('keyup', displayMatches);
67+
68+
</script>
69+
</body>
70+
</html>

0 commit comments

Comments
 (0)