Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 14fa4d8

Browse filesBrowse files
author
Richard Hart
committed
Day 6.
1 parent 4c24864 commit 14fa4d8
Copy full SHA for 14fa4d8

File tree

Expand file treeCollapse file tree

1 file changed

+34
-0
lines changed
Open diff view settings
Filter options
Expand file treeCollapse file tree

1 file changed

+34
-0
lines changed
Open diff view settings
Collapse file

‎06 - Type Ahead/index-START.html‎

Copy file name to clipboardExpand all lines: 06 - Type Ahead/index-START.html
+34Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,40 @@
1717
<script>
1818
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
1919

20+
const cities = [];
21+
22+
fetch(endpoint).then(blob => blob.json())
23+
.then(data => cities.push(...data));
24+
25+
function findMatches(wordToMatch, cities) {
26+
return cities.filter(place => {
27+
const regex = new RegExp(wordToMatch, 'gi');
28+
return place.city.match(regex) || place.state.match(regex);
29+
});
30+
}
31+
32+
function displayMatches() {
33+
const matchArray = findMatches(this.value, cities);
34+
const html = matchArray.map(place => {
35+
const regex = new RegExp(this.value, 'gi');
36+
const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
37+
const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
38+
return `
39+
<li>
40+
<span class="name">${cityName}, ${stateName}</span>
41+
<span class="population">${place.population}</span>
42+
</li>
43+
`;
44+
}).join('');
45+
suggestions.innerHTML = html;
46+
}
47+
48+
const searchInput = document.querySelector('.search');
49+
const suggestions = document.querySelector('.suggestions');
50+
51+
searchInput.addEventListener('change', displayMatches);
52+
searchInput.addEventListener('keyup', displayMatches);
53+
2054
</script>
2155
</body>
2256
</html>

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.