Skip to content

Commit 884582c

Browse files
committed
six complete
1 parent a0994ff commit 884582c

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

06 - Type Ahead/index-START.html

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

20+
const cities = [];
21+
22+
fetch(endpoint)
23+
// .then(blob => console.log(blob))
24+
.then(blob => blob.json())
25+
// .then(data => console.log(data))
26+
.then(data => cities.push(...data))
27+
//fetch itself will return a promise
28+
29+
30+
//matching function
31+
function findMatches(wordToMatch, cities){
32+
return cities.filter(place => {
33+
//if city matches search
34+
const regex = new RegExp(wordToMatch, 'gi');
35+
//global and insensitive so disregards case
36+
return place.city.match(regex) || place.state.match(regex);
37+
//will check if city or state has either one
38+
//filter will be run
39+
})
40+
}
41+
42+
function numbWithCommas(x){
43+
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
44+
}
45+
46+
47+
//display function
48+
function displayMatches() {
49+
console.log(this.value);
50+
const matchArray = findMatches(this.value, cities)
51+
console.log(matchArray);
52+
const html = matchArray.map(place => {
53+
//.replace lines to highlight the matched input
54+
const regex = new RegExp(this.value, 'gi');
55+
const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
56+
const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
57+
return `
58+
<li>
59+
<span class="name">${cityName}, ${stateName}</span>
60+
<span class="population">${numbWithCommas(place.population)}</span>
61+
</li>
62+
`;
63+
}).join(''); // .map returns an array so this will make it a string
64+
suggestions.innerHTML = html;
65+
}
66+
67+
//what is being searched
68+
const searchInput = document.querySelector('.search');
69+
const suggestions = document.querySelector('.suggestions');
70+
71+
searchInput.addEventListener('change', displayMatches);
72+
//change event only fires when you go off that input
73+
searchInput.addEventListener('keyup', displayMatches);
74+
75+
2076
</script>
2177
</body>
2278
</html>

0 commit comments

Comments
 (0)