-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
51 lines (43 loc) · 1.69 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
const countriesContainer = document.querySelector('.countries-container')
const filterByRegion = document.querySelector('.filter-by-region')
const searchInput = document.querySelector('.search-container input')
const themeChanger = document.querySelector('.theme-changer')
let allCountriesData
fetch('https://restcountries.com/v3.1/all')
.then((res) => res.json())
.then((data) => {
renderCountries(data)
allCountriesData = data
})
filterByRegion.addEventListener('change', (e) => {
fetch(`https://restcountries.com/v3.1/region/${filterByRegion.value}`)
.then((res) => res.json())
.then(renderCountries)
})
function renderCountries(data) {
countriesContainer.innerHTML = ''
data.forEach((country) => {
const countryCard = document.createElement('a')
countryCard.classList.add('country-card')
countryCard.href = `country.html?name=${country.name.common}`
countryCard.innerHTML = `
<img src="${country.flags.svg}" alt="${country.name.common} flag" />
<div class="card-text">
<h3 class="card-title">${country.name.common}</h3>
<p><b>Population: </b>${country.population.toLocaleString(
'en-IN'
)}</p>
<p><b>Region: </b>${country.region}</p>
<p><b>Capital: </b>${country.capital?.[0]}</p>
</div>
`
countriesContainer.append(countryCard)
})
}
searchInput.addEventListener('input', (e) => {
const filteredCountries = allCountriesData.filter((country) => country.name.common.toLowerCase().includes(e.target.value.toLowerCase()))
renderCountries(filteredCountries)
})
themeChanger.addEventListener('click', () => {
document.body.classList.toggle('dark')
})