(() => {
const $fetch = document.getElementById("countries"),
$fragment = document.createDocumentFragment();
async function getData($url, $method) {
try {
const res = await fetch( $url, {
method: $method,
});
let data = await res.json();
if (!res.ok) throw { status: res.status, statusText: res.statusText };
return data;
} catch (err) {
console.log(err);
let message = err.statusText || "Unexpected error";
let data = `Error ${err.status}: ${message}`;
return data;
}
};
// Run getData
getData('https://restcountries.com/v3.1/all', 'GET').then( (data) => {
data.forEach((el) => {
const $country = document.createElement("article");
$country.classList.add("item-box");
$country.innerHTML = `
${el.name.common}
Population
${el.population}
×
General information for Country - ${el.name.common}
Country |
Capital |
Region |
${el.name.common} |
${el.capital} |
${el.region} |
`;
$fragment.appendChild($country);
});
$fetch.appendChild($fragment);
});
// Modal
document.addEventListener('click', function (e) {
e = e || window.event;
let target = e.target || e.srcElement;
if (target.dataset.target && target.dataset.target !== '') {
let modalId = target.dataset.target;
document.getElementById(modalId).classList.add('open');
e.preventDefault();
}
// }
if (target.dataset.iframe && target.dataset.iframe !== '' && target.dataset.src && target.dataset.src !== '') {
document.getElementById(target.dataset.iframe).src = target.dataset.src;
}
if (target.dataset.dimensions && target.dataset.dimensions !== "") {
// alert(target.dataset.dimensions);
document.querySelector(`#${target.dataset.target}.modal-window`).setAttribute('style', target.dataset.dimensions);
if (target.dataset.iframe && target.dataset.iframe !== '' && target.dataset.src && target.dataset.src !== '') {
document.getElementById(target.dataset.iframe).setAttribute('style', target.dataset.dimensions);
}
document.querySelector(`#${target.dataset.target}.modal-window`).setAttribute('style', target.dataset.dimensions);
}
if (target.dataset.reload && target.dataset.reload === '1') {
document.querySelector('.close-modal').dataset.reload = 1;
}
// Close modal window with 'data-dismiss' attribute or when the backdrop is clicked
if ((target.hasAttribute('data-dismiss') && target.getAttribute('data-dismiss') == 'modal') || target.classList.contains('modal')) {
if (target.dataset.reload && target.dataset.reload === '1') {
parent.location.reload(true);
let modal = document.querySelector('[class="modal open"]');
modal.classList.remove('open');
e.preventDefault();
} else {
let modal = document.querySelector('[class="modal open"]');
modal.classList.remove('open');
e.preventDefault();
}
}
}, false);
document.body.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
if (document.querySelector('.close-modal')) {
document.querySelector('.close-modal').click();
}
}
});
})();