-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
64 lines (53 loc) · 1.91 KB
/
main.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
57
58
59
60
61
62
63
64
const base_url = "https://api.jikan.moe/v3";
function searchAnime(event) {
event.preventDefault();
const form = new FormData(this);
const query = form.get("search");
fetch(`${base_url}/search/anime?q=${query}&page=1`)
.then((res) => res.json())
.then(updateDom)
.catch((err) => console.warn(err.message));
}
function updateDom(data) {
const searchResults = document.getElementById("search-results");
const animeByCategories = data.results.reduce((acc, anime) => {
const { type } = anime;
if (acc[type] === undefined) acc[type] = [];
acc[type].push(anime);
return acc;
}, {});
searchResults.innerHTML = Object.keys(animeByCategories)
.map((key) => {
const animesHTML = animeByCategories[key]
.sort((a, b) => a.episodes - b.episodes)
.map((anime) => {
return `
<div class="card">
<div class="card-image yellow darken-3">
<img src="${anime.image_url}">
</div>
<div class="card-content">
<span class="card-title yellow-text text-darken-3">${anime.title}</span>
<p>${anime.synopsis}</p>
</div>
<div class="card-action">
<a href="${anime.url}">Find out more</a>
</div>
</div>
`;
})
.join("");
return `
<section>
<h3 class="category-title">${key.toUpperCase()}</h3>
<div class="animes-row row">${animesHTML}</div>
</section>
`;
})
.join("");
}
function pageLoaded() {
const form = document.getElementById("search_form");
form.addEventListener("submit", searchAnime);
}
window.addEventListener("load", pageLoaded);