-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
79 lines (60 loc) · 2.1 KB
/
Copy pathscript.js
File metadata and controls
79 lines (60 loc) · 2.1 KB
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
const container = document.getElementById("countriesContainer");
const loading = document.getElementById("loader");
const searchInput = document.getElementById("search");
const regionFilter = document.getElementById("regionFilter");
let allCountries = [];
async function getCountries() {
loading.style.display = "block";
try {
const res = await fetch("https://restcountries.com/v3.1/all?fields=name,capital,currencies,population,flags,region");
const data = await res.json();
allCountries = data;
showCountries(allCountries);
} catch (error) {
container.innerHTML = "Error loading data";
}
loading.style.display = "none";
}
function showCountries(countries) {
container.innerHTML = "";
countries.map(country => {
let currency = "N/A";
if (country.currencies) {
const key = Object.keys(country.currencies)[0];
currency = country.currencies[key].name;
}
const div = document.createElement("div");
div.className = "card";
div.innerHTML = `
<img src="${country.flags.png}" />
<h3>${country.name.common}</h3>
<p>Region: ${country.region}</p>
<p>Capital: ${country.capital ? country.capital[0] : "N/A"}</p>
<p>Population: ${country.population}</p>
<p>Currency: ${currency}</p>
<button onclick="addFavorite('${country.name.common}')">❤️ Favorite</button>
`;
container.appendChild(div);
});
}
searchInput.addEventListener("input", () => {
const value = searchInput.value.toLowerCase();
const filtered = allCountries.filter(c =>
c.name.common.toLowerCase().includes(value)
);
showCountries(filtered);
});
regionFilter.addEventListener("change", () => {
const region = regionFilter.value;
const filtered = region
? allCountries.filter(c => c.region === region): allCountries;
showCountries(filtered);
});
function sortByPopulation() {
const sorted = [...allCountries].sort((a, b) => b.population - a.population);
showCountries(sorted);}
function addFavorite(name) {alert(name + " added to favorites");}
function toggleDarkMode() {
document.body.classList.toggle("dark");
}
getCountries();