Skip to main content

Task 20: Fun Fact Generator using Useless Facts API

Start with Affirmation​

  • I declare that today I operate in purpose, not pressure.

  • I declare that I have what it takes to solve challenges creatively.

  • I declare that every line of code I write adds value and builds momentum.

  • I declare that growth is happening—visible or not, I am advancing.

  • I declare that I approach Task 20 with clarity, curiosity, and confidence.

  • I declare that learning is my superpower, and I’m getting better every day.

  • I declare that I’m not just completing a task—I’m building a skill, a habit, a future.

  • I declare that distractions are beneath me—I choose excellence and joy.

💪 Repeat daily, feel the power, and watch your success unfold!


🔹 If you don’t understand the task, watch the video above for the answer.


Task​

Want to make your JavaScript projects more fun? In this beginner-friendly tutorial, we’ll build a Fun Fact Generator using the Useless Facts API and JavaScript! 🧠💡

  • How to use fetch() to make API calls

  • How to work with JSON data in JavaScript

  • How to update the DOM dynamically

  • How to handle errors and user interactions


** Step 1: HTML​

<h1>🎉 Fun Fact Generator</h1>
<button id="getFactBtn">Get Fun Fact</button>
<p id="fact">Click the button to learn something fun! 🧠</p>

<!-- Axios CDN -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="script.js"></script>


Step 2: JS​

// Step 1: Grab DOM elements
const getFactBtn = document.getElementById("getFactBtn");
const fact = document.getElementById("fact");

// Step 2: Add event listener to button
getFactBtn.addEventListener("click", getFunFact);

// Step 3: Fetch random fact using Axios
function getFunFact() {
axios.get("https://uselessfacts.jsph.pl/api/v2/facts/random?language=en")
.then(response => {
fact.textContent = `💬 ${response.data.text}`;
})
.catch(error => {
console.error("Error fetching fact:", error);
fact.textContent = "Oops! Couldn't fetch a fun fact. Try again.";
});
}

What You'll Learn:​

  • How to use Axios to make a GET request
  • How to update the DOM dynamically
  • How to handle API errors gracefully