-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
76 lines (64 loc) · 2.3 KB
/
app.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
import { fetchCountries } from "./api.js";
import { displayCountries, filterCountries, renderPagination } from "./ui.js";
let countries = [];
let currentPage = 1;
const itemsPerPage = 20;
async function init() {
countries = await fetchCountries();
displayCountries(paginate(countries, currentPage));
renderPagination(countries.length, itemsPerPage, paginateAndDisplay);
}
function paginate(countries, page) {
const start = (page - 1) * itemsPerPage;
const end = page * itemsPerPage;
return countries.slice(start, end);
}
function paginateAndDisplay(page) {
currentPage = page;
displayCountries(paginate(countries, currentPage));
}
document.getElementById("search").addEventListener("input", (e) => {
const filteredCountries = filterCountries(countries, e.target.value);
if (filteredCountries.length > 0) {
displayCountries(paginate(filteredCountries, 1));
renderPagination(
filteredCountries.length,
itemsPerPage,
paginateAndDisplay
);
document.getElementById("no-results").style.display = "none";
document.getElementById("pagination").style.display = "block";
} else {
document.getElementById("countries-container").innerHTML = "";
document.getElementById("no-results").style.display = "block";
document.getElementById("pagination").style.display = "none";
}
});
document.getElementById("sort").addEventListener("change", (e) => {
countries = sortCountries(countries, e.target.value);
displayCountries(paginate(countries, currentPage));
});
document.getElementById("theme-toggle").addEventListener("click", () => {
const body = document.body;
const themeIcon = document.getElementById("theme-icon");
body.dataset.theme = body.dataset.theme === "dark" ? "light" : "dark";
if (body.dataset.theme === "dark") {
themeIcon.classList.remove("fa-sun");
themeIcon.classList.add("fa-moon");
} else {
themeIcon.classList.remove("fa-moon");
themeIcon.classList.add("fa-sun");
}
});
function sortCountries(countries, criterion) {
return countries.sort((a, b) => {
if (criterion === "population") {
return b.population - a.population;
} else if (criterion === "name") {
return a.name.common.localeCompare(b.name.common);
} else if (criterion === "region") {
return a.region.localeCompare(b.region);
}
});
}
init();