-
Notifications
You must be signed in to change notification settings - Fork 0
/
index-START.html
executable file
·65 lines (56 loc) · 2.21 KB
/
index-START.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
65
<!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';
const cities = [];
//fetch will retturn a promise -- data which comes back from the fetch
fetch(endpoint)
.then(blob => blob.json()) // dont know what type of data is it. has to be converted from raw to json. blob has a json() and it returns a promise
.then(data => cities.push(...data)) // use spread(...) to make this array into individual args
//find the searched word in the cities array
function findMatches(wordToMatch, cities){
return cities.filter(place => {
//figure out if the city or state matches what was searched
const regex = new RegExp(wordToMatch, 'gi');//global insensitive
return place.city.match(regex) || place.state.match(regex)
});
}
function numberWithCommas(x) { // from stack overflow
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
//list search results
function displayMatches(){
const matchArray = findMatches(this.value, cities);
const html = matchArray.map(place => {
const regex = new RegExp(this.value, 'gi');
const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`); //replace matched city name with .hl
const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`); //replace matched city name with .hl
return `
<li>
<span class="name">${cityName /* place.city changed with cityName */}, ${stateName}</span>
<span class="population">${numberWithCommas(place.population)}</span>
</li>
`;
}).join('');
suggestions.innerHTML = html;
}
const searchInput = document.querySelector('.search');
const suggestions = document.querySelector('.suggestions');
searchInput.addEventListener("change", displayMatches);
searchInput.addEventListener("keyup", displayMatches);
</script>
</body>
</html>