I am making a website where you can search through all the countries in the world. Once you have found a country you want more detail about you should be able to click and view a detailed page with more info.
I am having trouble updating the countries that are currently shown with the user's restrictions. I want to add an eventListener to every active card to be able to open the detail page for that specific country. Is there a way to do it without an interval function checking every other second? I have a feeling this is not the correct way.
Here is the interval function:
function updateActiveCards(){
activeCards = Array.from(document.querySelectorAll('.search-result-card'));
}
setInterval(updateActiveCards, 1000);
Here is an example of how a search result would look
All the added cards get a class of 'search-result-card' and they are added by this code:
async function loadCountriesByName(name){
const respone = await fetch('https://restcountries.com/v2/name/' + name);
const data = await respone.json();
data.map(element => {
addCountry(element);
});
}
async function loadAllCountries(){
const response = await fetch('https://restcountries.com/v2/all');
const data = await response.json();
data.map(element => {
addCountry(element);
});
}
searchBar.addEventListener('input', () => {
const currentValue = searchBar.value;
if(currentValue == ''){
results.innerHTML = '';
loadAllCountries();
} else {
results.innerHTML = '';
loadCountriesByName(currentValue);
}
});
function addCountry(CountryData){
const newCard = document.createElement('div');
newCard.classList.add('search-result-card');
newCard.innerHTML = `
<div class="country-img">
<img src="${CountryData.flag}" alt="">
</div>
<div class="country-info">
<h2>${CountryData.name}</h2>
<h3>Population: <span>81,770,900</span></h3>
<h3>Region: <span>Europe</span></h3>
<h3>Capital: <span>Berlin</span></h3>
</div>
`
results.append(newCard);
}
loadAllCountries()
Thanks in advance!