-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
39 lines (33 loc) · 1.2 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
let characters = [];
let matchingCharacters = [];
const charactersList = document.querySelector("#charactersList")
document.addEventListener('DOMContentLoaded', getCharacters)
async function getCharacters() {
let url = 'https://swapi2.azurewebsites.net/api/characters';
try {
const fetchedCharacters = await fetch(url)
.then(res => res.json())
characters.push(...fetchedCharacters);
}
catch (ex) {
console.error("Error reading characters.", ex.message);
}
console.log("All the characters are ", characters)
renderCharacters(characters);
}
const filterCharacters = () => {
const searchString = document.querySelector("#searchString").value;
const re = new RegExp(searchString, "i");
matchingCharacters = characters.filter(character => re.test(character.name))
renderCharacters(matchingCharacters);
}
const renderCharacters = characters => {
const divs = characters.map(character => {
const el = document.createElement('div');
el.addEventListener('click', () => goToCharacterPage(character.id));
el.textContent = character.name;
return el;
})
charactersList.replaceChildren(...divs)
}
const goToCharacterPage = id => window.location = `/character.html?id=${id}`