|
| 1 | +<!DOCTYPE html> |
| 2 | +<html lang="en"> |
| 3 | +<head> |
| 4 | + <meta charset="UTF-8"> |
| 5 | + <title>Type Ahead 👀</title> |
| 6 | + <link rel="stylesheet" href="style.css"> |
| 7 | +</head> |
| 8 | +<body> |
| 9 | + |
| 10 | + <form class="search-form"> |
| 11 | + <input type="text" class="search" placeholder="City or State"> |
| 12 | + <ul class="suggestions"> |
| 13 | + <li>Filter for a city</li> |
| 14 | + <li>or a state</li> |
| 15 | + </ul> |
| 16 | + </form> |
| 17 | +<script> |
| 18 | + |
| 19 | +const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json'; |
| 20 | +const cities = []; |
| 21 | +const searchInput = document.querySelector('.search'); |
| 22 | +const suggestions = document.querySelector('.suggestions'); |
| 23 | + |
| 24 | +fetch(endpoint) |
| 25 | + .then(blob => blob.json()) |
| 26 | + .then(data => cities.push(...data)) |
| 27 | + |
| 28 | +const numberWithCommas = x => x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); |
| 29 | + |
| 30 | +const findMatches = (wordsToMatch, cities) => |
| 31 | + cities.filter(place => { |
| 32 | + const regex = new RegExp(wordsToMatch, 'gi'); |
| 33 | + return place.city.match(regex) || place.state.match(regex); |
| 34 | + }); |
| 35 | + |
| 36 | +const displayMatches = element => { |
| 37 | + const matchArray = findMatches(element.value, cities); |
| 38 | + const html = matchArray.map(place => { |
| 39 | + const regex = new RegExp(element.value, 'gi'); |
| 40 | + const cityName = place.city.replace(regex, `<span class="hl">${element.value}</span>`) |
| 41 | + const stateName = place.state.replace(regex, `<span class="hl">${element.value}</span>`) |
| 42 | + return `<li> |
| 43 | + <span class="city">${cityName}, ${stateName}</span> |
| 44 | + <span class="population">${numberWithCommas(place.population)}</span> |
| 45 | + </li>`; |
| 46 | + }).join(''); |
| 47 | + suggestions.innerHTML = html; |
| 48 | +} |
| 49 | + |
| 50 | + |
| 51 | +searchInput.addEventListener('change', () => displayMatches(searchInput)); |
| 52 | +searchInput.addEventListener('keyup', () => displayMatches(searchInput)); |
| 53 | + |
| 54 | +</script> |
| 55 | + </body> |
| 56 | +</html> |
0 commit comments