|
| 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 | + <link rel="icon" href="https://fav.farm/🔥" /> |
| 8 | +</head> |
| 9 | +<body> |
| 10 | + |
| 11 | + <form class="search-form"> |
| 12 | + <input type="text" class="search" placeholder="Capital or Country"> |
| 13 | + <ul class="suggestions"> |
| 14 | + <li>Filter for a capital</li> |
| 15 | + <li>or a country</li> |
| 16 | + </ul> |
| 17 | + </form> |
| 18 | +<script> |
| 19 | +const endpoint = 'https://api.sampleapis.com/countries/countries'; |
| 20 | + |
| 21 | +const capitals = []; |
| 22 | + |
| 23 | +fetch(endpoint) |
| 24 | + .then(blob => blob.json()) |
| 25 | + .then(data => capitals.push(...data)) |
| 26 | + |
| 27 | +function findMatches(wordToMatch, countries) { |
| 28 | + return countries.filter(place => { |
| 29 | + const regex = new RegExp(wordToMatch, 'gi'); |
| 30 | + return place.name.match(regex) || (place.capital && place.capital.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 | + |
| 40 | + const matchArray = findMatches(this.value, capitals); |
| 41 | + const html = matchArray.map(place => { |
| 42 | + const regex = new RegExp(this.value, 'gi'); |
| 43 | + const capitalName = place.name.replace(regex, `<span class="hl">${this.value}</span>`); |
| 44 | + const countryName = (place.capital || '').replace(regex, `<span class="hl">${this.value}</span>`); |
| 45 | + return ` |
| 46 | + <li> |
| 47 | + <span class="name">${capitalName}, ${countryName}</span> |
| 48 | + <span class="population">${place.population ? numberWithCommas(place.population) : 'N/A'}</span> |
| 49 | + </li> |
| 50 | + `; |
| 51 | + }).join(''); |
| 52 | + suggestions.innerHTML = html; |
| 53 | +} |
| 54 | + |
| 55 | +const searchInput = document.querySelector('.search'); |
| 56 | +const suggestions = document.querySelector('.suggestions'); |
| 57 | + |
| 58 | +searchInput.addEventListener('change', displayMatches); |
| 59 | +searchInput.addEventListener('keyup', displayMatches); |
| 60 | + |
| 61 | + |
| 62 | + |
| 63 | +</script> |
| 64 | +</body> |
| 65 | +</html> |
0 commit comments