-
Notifications
You must be signed in to change notification settings - Fork 0
/
custom.js
91 lines (82 loc) · 2.6 KB
/
custom.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
let container = document.querySelector(".pokemons");
let selectPage = document.querySelector("#limit");
let navigation = document.querySelector(".navigation .numbers");
let pokemons = [];
const pokeUrl = "https://pokeapi.co/api/v2/";
let prevLink = "";
let nextLink = "";
let count = 0;
let perPage = 40;
let currentPage = 0;
const changePg = (value) => {
//console.log("value: ", value);
let newUrl = `${pokeUrl}pokemon?limit=${value}`;
perPage = value;
getPokemons(newUrl);
}
const prev = () => {
getPokemons(prevLink);
}
const next = () => {
getPokemons(nextLink);
}
const getPokemons = (url) => {
let params = new URLSearchParams(url.split('?')[1]);
let offset = params.get('offset');
currentPage = offset / perPage;
fetch(url)
.then(response => response.json())
.then(responseJson => {
prevLink = responseJson.previous;
nextLink = responseJson.next;
count = responseJson.count;
addNumbers(count);
showPokemons(responseJson.results);
})
}
const showPokemons = (array) => {
clearContainer();
array.map(item => {
fetch(item.url)
.then(response => response.json())
.then(data => {
//console.log("data: ", data)
loadCard(data);
})
})
}
const loadCard = (data) => {
const image = data.sprites.other.home.front_default;
let newImage = image ? image : '/images/default.png';
let card = document.createElement("div");
let content = `
<img src="${newImage}" alt="${data.name}">
<p>${data.name}</p>
<p class="order"> #${data.order}</p>
`;
card.innerHTML = content;
container.appendChild(card);
}
const clearContainer = () => container.innerHTML = "";
const clearNavigation = () => navigation.innerHTML="";
const addNumbers = (count) => {
clearNavigation();
const pages = count/perPage;
for (let index = 0; index < pages; index++) {
let number = document.createElement("span");
number.classList.add(`element-${index}`);
const numLink = `<button onclick="actionNumber(${index})">${index+1}</button>`
number.innerHTML = numLink;
navigation.appendChild(number);
}
addFocusClass();
}
const actionNumber = (index) => {
const newLink = `https://pokeapi.co/api/v2/pokemon?offset=${index*perPage}&limit=${perPage}`;
getPokemons(newLink);
}
const addFocusClass = () => {
const span = document.querySelector(`.element-${currentPage}`);
span.classList.add("current");
}
getPokemons(`${pokeUrl}pokemon?offset=0&limit=40`);