-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
56 lines (43 loc) · 1.66 KB
/
script.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
const rootElement = document.querySelector("#root")
const fetchUrl = (url) => fetch(url).then(res => res.json())
const skeletonComponent = () => `
<div class="characters"></div>
<div class="buttons"></div>
`
const characterComponent = (characterData) => `
<div class="char">
<img src=${characterData.image}>
<h2>${characterData.name}</h2>
<h3>appears in: ${characterData.episode.length} episodes</h3>
</div>
`
const buttonComponent = (id, text) => `<button id=${id}>${text}</button>`
const buttonEventComponent = (id, url) => {
const buttonElement = document.querySelector(`#${id}`)
buttonElement.addEventListener("click", () => {
console.log(`fetch: ${url}`)
rootElement.innerHTML = "LOADING..."
fetchUrl(url).then(data => makeDomFromData(data, rootElement))
})
}
const makeDomFromData = (data, rootElement) => {
rootElement.innerHTML = skeletonComponent()
const charactersElement = document.querySelector(".characters")
const buttonsElement = document.querySelector(".buttons")
const info = data.info
const characters = data.results
characters.forEach(character => charactersElement.insertAdjacentHTML("beforeend", characterComponent(character)))
if (info.prev) {
buttonsElement.insertAdjacentHTML("beforeend", buttonComponent("prev", "previous"))
buttonEventComponent("prev", info.prev)
}
if (info.next) {
buttonsElement.insertAdjacentHTML("beforeend", buttonComponent("next", "next"))
buttonEventComponent("next", info.next)
}
}
const init = () => {
rootElement.innerHTML = "LOADING..."
fetchUrl("https://rickandmortyapi.com/api/character").then(data => makeDomFromData(data, rootElement))
}
init()