Skip to content

Instantly share code, notes, and snippets.

@BRAVO68WEB
Created December 4, 2020 11:31
Show Gist options
  • Save BRAVO68WEB/5e986edb1c34c374fd0877f550df051f to your computer and use it in GitHub Desktop.
Save BRAVO68WEB/5e986edb1c34c374fd0877f550df051f to your computer and use it in GitHub Desktop.
Ajax search using Fetch API
<section class="search">
<input class="search__input" type="text" />
<ul class="results"></ul>
</section>
const input = document.querySelector('input');
const resultContainer = document.querySelector('.results');
const url = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
const cities = [];
fetch(url)
.then(blob => blob.json())
.then(data => cities.push(...data));
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);
const html = matchArray.map((result) => {
return `
<li class="result">
<div class="result__top">
<h2 class="result__city">${result.city}</h2>
<span class="result__polulation">${result.population.replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</span>
</div>
<span class="result__state">${result.state}</span>
</li>`
}).join('');
resultContainer.innerHTML = html;
}
input.addEventListener('change', displayMatches);
input.addEventListener('keyup', displayMatches);
@use postcss-cssnext;
* {
box-sizing: border-box;
}
body {
background: linear-gradient(90deg, rgba(66,77,109,1) 0%,rgba(62,70,90,1) 100%);
font-family: avenir, helvetica, arial, sans-serif;
letter-spacing: 1px;
}
.search {
width: 500px;
margin: 50px auto;
}
.search__input {
background-color: #2a3040;
border: 0;
padding: 15px 20px;
width: 100%;
margin: 0;
color: white;
font-size: 26px;
font-weight: bold;
text-transform: uppercase;
font-family: avenir, helvetica, arial, sans-serif;
&:focus {
outline: 0;
box-shadow:0px 1px 0px #ccc;
}
}
.results {
padding: 0;
}
.result {
color: #656e80;
background-color: #2a3040;
list-style: none;
width: 500px;
padding: 10px 10px 10px 25px;
position: relative;
&:not(:last-child) {
border-bottom: 1px solid #373d4e;
}
&:before {
position: absolute;
width: 3px;
content: '';
background-color: #5073dd;
top: 15px;
left: 10px;
bottom: 15px;
}
}
.result__top {
justify-content: space-between;
display: flex;
align-items: flex-start;
}
.result__city {
color: white;
margin: 0;
}
.result__polulation {
font-size: 13px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment