Task 13: π Country Facts β Learn About a Country Using JavaScript & API
Start with Thanksgivingβ
- "I am destined for greatness. Every step I take brings me closer to my goals. I embrace challenges, knowing they are stepping stones to success. My mind is focused, my heart is determined, and my actions are aligned with my dreams."
Daily Affirmations for Success
- β I am capable, confident, and unstoppable.
- β Success flows to me because I take consistent action.
- β I attract opportunities that align with my purpose.
- β My hard work and persistence create abundance.
- β I am always learning, growing, and evolving.
- β I believe in my potential and trust my journey.
- β I turn setbacks into comebacks with resilience.
- β I am grateful for every success, big and small.
Success Reflectionβ
"Every effort I made today has planted seeds for my future success. I release any doubts and trust the process. My dreams are possible, and I am getting closer every day. I am grateful, I am strong, and I am ready for more!"
πͺ Repeat daily, feel the power, and watch your success unfold!
Task Answer - Video Linkβ
πΉ If you donβt understand the task, watch the video above for the answer.
Taskβ
** Step 1: Set up the HTMLβ
What youβll learn:
How to take input from a user
How to use fetch() to call a public API
How to display data like capital, population, flag, and region Letβs dive in! π»π
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>π Country Facts</title>
</head>
<body>
<h1>π Country Facts</h1>
<input type="text" id="countryInput" placeholder="Enter country name" />
<button id="searchBtn">π Search</button>
<div id="result"></div>
<script src="script.js"></script>
</body>
</html>
Step 2: JavaScriptβ
// Get elements from the DOM
const searchBtn = document.getElementById("searchBtn");
const countryInput = document.getElementById("countryInput");
const result = document.getElementById("result");
// Add event listener to the button
searchBtn.addEventListener("click", fetchCountry);
// Function to get country data
function fetchCountry() {
const country = countryInput.value.trim(); // Get input text
if (country === "") {
result.innerHTML = "β Please enter a country name.";
return;
}
// REST Countries API
fetch(`https://restcountries.com/v3.1/name/${country}`)
.then(response => {
if (!response.ok) {
throw new Error("Country not found.");
}
return response.json();
})
.then(data => {
const info = data[0];
const name = info.name.common;
const capital = info.capital ? info.capital[0] : "N/A";
const region = info.region;
const population = info.population.toLocaleString();
const flag = info.flags.png;
result.innerHTML = `
<h2>${name}</h2>
<p>ποΈ Capital: ${capital}</p>
<p>π Region: ${region}</p>
<p>π₯ Population: ${population}</p>
<img src="${flag}" alt="Flag of ${name}" width="200" />
`;
})
.catch(error => {
console.error(error);
result.innerHTML = "β οΈ Country not found. Please try again.";
});
}