-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
66 lines (57 loc) · 1.83 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
57
58
59
60
61
62
63
64
65
66
const dataBaseApiUrl =
"https://api.sheety.co/30b6e400-9023-4a15-8e6c-16aa4e3b1e72";
let jsonRoomsData;
let currentPage = 1;
const getJsonUrl = async (url) => {
let response = await fetch(url);
if (!response.ok) response = await fetch("data.json");
const textResponse = await response.text();
return JSON.parse(textResponse);
};
const paginateArray = (array, itemsPerPage) => {
return array.reduce((total, current, index) => {
const belongArray = Math.ceil((index + 1) / itemsPerPage) - 1;
total[belongArray]
? total[belongArray].push(current)
: total.push([current]);
return total;
}, []);
};
const renderPage = () => {
document.getElementById("script").innerHTML = `${jsonRoomsData[--currentPage]
.map(function (room) {
return `
<div class="card">
<div class="cardImg">
<img
src=${room.photo}
/>
</div>
<div class="cardText">
<div>${room.property_type}</div>
<div>${room.name}</div>
<div>R$: ${room.price}</div>
</div>
</div>`;
})
.join("")}`;
};
const createPaginationMenu = async () => {
jsonRoomsData = await getJsonUrl(dataBaseApiUrl);
jsonRoomsData = paginateArray(jsonRoomsData, 8);
renderPage()
let paginationMenu = document.querySelector(".pagination-menu");
let pages = [];
if (jsonRoomsData.length > 1) {
for (let i = 0; i < jsonRoomsData.length; i++) {
pages.push(document.createElement("button"));
pages[i].innerHTML = i + 1;
pages[i].addEventListener('click', () => {
currentPage = i + 1;
renderPage()
});
paginationMenu.appendChild(pages[i]);
}
}
};
createPaginationMenu();