Skip to content

Commit f6c7cfa

Browse files
author
nrvarun
committed
Day 6 Completed
1 parent a94dfef commit f6c7cfa

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

06 - Type Ahead/index-START.html

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,46 @@
1717
<script>
1818
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
1919

20+
let cities = [];
21+
22+
fetch(endpoint)
23+
.then(res => res.json())
24+
.then( (res) => { console.log(res); cities = res; } );
25+
26+
function findMatches(wordToMatch, cities) {
27+
return cities.filter(place => {
28+
// here we need to figure out if the city or state matches what was searched
29+
const regex = new RegExp(wordToMatch, 'gi');
30+
return place.city.match(regex) || place.state.match(regex)
31+
});
32+
}
33+
34+
function numberWithCommas(x) {
35+
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
36+
}
37+
38+
function displayMatches() {
39+
const matchArray = findMatches(this.value, cities);
40+
const html = matchArray.map(place => {
41+
const regex = new RegExp(this.value, 'gi');
42+
const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
43+
const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
44+
return `
45+
<li>
46+
<span class="name">${cityName}, ${stateName}</span>
47+
<span class="population">${numberWithCommas(place.population)}</span>
48+
</li>
49+
`;
50+
}).join('');
51+
suggestions.innerHTML = html;
52+
}
53+
54+
const searchInput = document.querySelector('.search');
55+
const suggestions = document.querySelector('.suggestions');
56+
57+
searchInput.addEventListener('change', displayMatches);
58+
searchInput.addEventListener('keyup', displayMatches);
59+
2060
</script>
2161
</body>
2262
</html>

06 - Type Ahead/style.css

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@
4141
margin: 0;
4242
padding: 0;
4343
position: relative;
44+
max-height: 322px;
45+
overflow: hidden;
4446
/*perspective:20px;*/
4547
}
4648
.suggestions li {

0 commit comments

Comments
 (0)