From 557a8c9c8369b9a1b062faa591da2245e92e06ab Mon Sep 17 00:00:00 2001 From: R0EYK Date: Thu, 12 Dec 2024 22:51:21 +0200 Subject: [PATCH] Fetching from JSON and Filtering --- index.html | 69 ++-------------------------------------------- scripts.js | 81 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 66 deletions(-) create mode 100644 scripts.js diff --git a/index.html b/index.html index f4afbf5..ddcaa59 100644 --- a/index.html +++ b/index.html @@ -86,73 +86,10 @@

Where in the world?

-
+ diff --git a/scripts.js b/scripts.js new file mode 100644 index 0000000..08d4cd2 --- /dev/null +++ b/scripts.js @@ -0,0 +1,81 @@ +// Load countries from JSON file, once completed use displayCountries to render them +const loadCountries = async () => { + const grid = document.getElementById("countries-grid"); + + try { + const response = await fetch("./CountriesData.json"); + const countries = await response.json(); + displayCountries(countries); + } catch (error) { + console.error("Error loading countries:", error); + } +}; + +const displayCountries = (countries) => { + const grid = document.getElementById("countries-grid"); + grid.innerHTML = ""; // Reset the grid + + countries.forEach((country) => { + const countryElement = document.createElement("a"); + countryElement.href = "#"; + countryElement.className = "country scale-effect"; + countryElement.setAttribute("data-country-name", country.name); + + countryElement.innerHTML = ` +
+ ${country.name} Flag +
+
+

${country.name}

+ +
+ `; + + // Append the country element to the grid + grid.appendChild(countryElement); + }); +}; + +const filterCountries = async (region) => { + try { + const response = await fetch("./CountriesData.json"); + const countries = await response.json(); + const filteredCountries = + region === "all" + ? countries + : countries.filter( + (country) => country.region.toLowerCase() === region + ); + displayCountries(filteredCountries); + } catch (error) { + console.error("Error filtering countries:", error); + } +}; + +// Load countries when the DOM is fully loaded +document.addEventListener("DOMContentLoaded", () => { + loadCountries(); + + const dropdownWrapper = document.querySelector(".dropdown-wrapper"); + const dropdownHeader = document.querySelector(".dropdown-header"); + const dropdownItems = document.querySelectorAll(".dropdown-body li"); + + dropdownHeader.addEventListener("click", () => { + dropdownWrapper.classList.toggle("open"); + }); + + dropdownItems.forEach((item) => { + item.addEventListener("click", (event) => { + const region = event.target.getAttribute("data-region"); + filterCountries(region); + dropdownWrapper.classList.remove("open"); // close the dropdown + }); + }); +});