Created
June 16, 2020 00:57
-
-
Save schinns/7e3ef51d6b9b3835dcc5ebc2e6a32769 to your computer and use it in GitHub Desktop.
Super basic vanilla js search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Star Wars Planets</title> | |
</head> | |
<body> | |
<h1>Star Wars Planets</h1> | |
<input id="search" type="text" /> | |
<button id="submit">search</button> | |
<ul id="planets"></ul> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script> | |
<script> | |
//set state | |
window.app = {} | |
//create planet list fn | |
const createPlanetList = (planets) => { | |
const ul = document.getElementById('planets') | |
console.log(planets) | |
planets.forEach(planet => { | |
const li = document.createElement('li') | |
li.textContent = planet.name | |
ul.appendChild(li) | |
}) | |
} | |
//make api call for planets | |
axios.get('https://swapi.dev/api/planets') | |
.then(payload => { | |
window.app.planets = payload.data.results | |
createPlanetList(window.app.planets) | |
}) | |
.catch(err => console.log(err)) | |
const input = document.getElementById('search') | |
const changeEventHandler = (event) => { | |
window.app.search = event.target.value | |
} | |
input.addEventListener('change', changeEventHandler) | |
const button = document.getElementById('submit') | |
console.log(button) | |
button.addEventListener('click', () => { | |
const newState = window.app.planets.filter(planet => planet.name.toLowerCase().includes(window.app.search.toLowerCase())) | |
console.log(newState) | |
//if the result is greater than 1, clear the ul to mount new list | |
if(newState.length > 0) { | |
document.getElementById('planets').innerHTML = '' | |
} | |
//mount new list | |
createPlanetList(newState) | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment