-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
224 lines (181 loc) · 5.18 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
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
const API_URL = "https://restcountries.com/v3.1/all";
const FIELDS =
"name,cca3,currencies,capital,region,population,continents,flags";
const filter = document.querySelector(".filter");
const gridContainer = document.querySelector(".grid-container");
const searchInput = document.getElementById("search");
const modal = document.querySelector(".modal");
//* variables
let countries = [];
let filteredCountries = [];
let search = null;
let continent = "All";
//* api functions
const fetchData = async (apiURL) => {
try {
const response = await fetch(apiURL);
return await response.json();
} catch (error) {
console.error("Error fetching data", error);
throw error;
}
};
const getCountries = async () => {
try {
const apiURL = `${API_URL}?fields=${FIELDS}`;
const data = await fetchData(apiURL);
return data.sort((a, b) => {
const nameA = a.name.common.toLowerCase();
const nameB = b.name.common.toLowerCase();
if (nameA < nameB) return -1;
if (nameA > nameB) return 1;
return 0;
});
} catch (error) {
return [];
}
};
//* render functions
const renderCountryList = () => {
// use fragment to temporary build the list
const fragment = document.createDocumentFragment();
filteredCountries.forEach((country) => {
// destructure
const {
name,
flags,
cca3,
capital,
population,
currencies,
region,
continents,
} = country;
// change currencies from object to array
const currencyList = Object.keys(currencies).map((code) => {
const { name } = currencies[code];
return `${name} (${code})`;
});
const gridItem = document.createElement("div");
gridItem.classList.add("grid-item");
gridItem.addEventListener("click", onGridItemClick);
gridItem.innerHTML = `
<a href="${flags.svg}">
<img
src="${flags.svg}"
alt="${name.common} (${cca3})"
/>
</a>
<div>
<h3>${name.common}</h3>
<p>
<label>Capital</label>
${capital.join(", ")}
</p>
<p>
<label>Population</label>
${population.toLocaleString("en")}
</p>
<p>
<label>Currencies</label>
${currencyList.join(", ")}
</p>
<p>
<label>Continent</label>
${continents.join(", ")}
</p>
</div>`;
fragment.appendChild(gridItem);
});
// add the virtual list to DOM
gridContainer.replaceChildren(fragment);
};
const renderFilterList = () => {
const optionList = filter.querySelector(".options");
// get the continents from countries and sort alphabetically
let continents = countries.flatMap((c) => c.continents).sort();
// prepend 'All' and remove duplicates
continents = ["All", ...new Set(continents)];
continents.forEach((continent) => {
const option = document.createElement("div");
option.textContent = continent;
option.addEventListener("click", onFilterOptionClick);
optionList.appendChild(option);
});
};
//* event handlers
const loadCountries = async () => {
countries = await getCountries();
filteredCountries = countries;
renderCountryList();
renderFilterList();
};
const handleEscapeKey = (e) => {
if (e.key === "Escape") {
modal.classList.remove("show");
}
};
const applyFilters = () => {
filteredCountries = countries;
if (search !== null) {
filteredCountries = filteredCountries.filter((country) => {
// name, capital, code
const name = country.name.common.toLowerCase();
const capital = country.capital.join(", ").toLowerCase();
const code = country.cca3.toLowerCase();
return (
name.includes(search) ||
capital.includes(search) ||
code.includes(search)
);
});
}
if (continent !== "All") {
filteredCountries = filteredCountries.filter((country) => {
return country.continents.includes(continent);
});
}
};
const onGridItemClick = (e) => {
e.preventDefault();
if (e.target.tagName === "IMG") {
const { src, alt } = e.target;
const img = modal.querySelector("img");
const dismiss = modal.querySelector("[data-dismiss]");
const caption = modal.querySelector("figcaption");
img.src = src;
img.alt = alt;
caption.textContent = alt;
dismiss.addEventListener("click", onDismissClick);
modal.classList.add("show");
}
};
const onDismissClick = () => {
modal.classList.remove("show");
};
const onFilterOptionClick = (e) => {
continent = e.target.textContent;
// Change the selected filter
const button = filter.querySelector("button");
button.textContent = continent;
// apply the search filter to filtered countries
applyFilters();
// re-render country list
renderCountryList();
};
const onFilterButtonClick = () => {
filter.classList.toggle("open");
};
const onSearchInput = () => {
search = searchInput.value.trim().toLowerCase();
// apply the search keyword to filtered countries
applyFilters();
// re-render country list
renderCountryList();
};
//* event listeners
document.addEventListener("keydown", handleEscapeKey);
filter.addEventListener("click", onFilterButtonClick);
searchInput.addEventListener("input", onSearchInput);
//* initialize
loadCountries();