Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions 06 - Type Ahead/changi.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<!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(endpoint)
.then((res) => res.json())
.then((data) => {
cities.push(...data);
});

function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

function findMatches(wordToMatch, cities) {
return cities.filter((place) => {
const regex = new RegExp(wordToMatch, "gi");
return place.city.match(regex) || place.state.match(regex);
});
}

function displayMatches() {
const matchArray = findMatches(this.value, cities);

matchArray.sort((a, b) => {
return a.city < b.city ? -1 : 1;
});

const html = matchArray
.map((place) => {
const regex = new RegExp(this.value, "gi");
const cityName = place.city.replace(
regex,
`<span class="hl">${this.value}</span>`
);
const stateName = place.state.replace(
regex,
`<span class="hl">${this.value}</span>`
);

return `
<li>
<span class="name">${cityName}, ${stateName}</span>
<span class="population">${numberWithCommas(
place.population
)}</span>
</li>
`;
})
.join("");
suggestions.innerHTML = html;
}

const searchInputs = document.querySelector(".search");
const suggestions = document.querySelector(".suggestions");

searchInputs.addEventListener("change", displayMatches);
searchInputs.addEventListener("keyup", displayMatches);
</script>
</body>
</html>