Skip to main content

Task 18: Learn JSON in JavaScript with a Life Advice App (No API Needed)

Start with Affirmation​

  • I declare that I am equipped with everything I need to complete this task with excellence.

  • I declare that clarity, creativity, and confidence flow through me as I work.

  • I declare that each challenge I face is a stepping stone to growth and mastery.

  • I declare that my efforts are not in vainβ€”every line I write and every concept I learn adds value.

  • I declare that I am becoming a better version of myself with each task I finish.

  • I declare that I am focused, fearless, and fully capable of achieving my goals.

  • I declare that I learn fast, adapt quickly, and move forward with purpose.

  • I declare that I choose progress over perfection and celebrate each small win.

  • I declare that I am committed to finishing strong and showing up with excellence.

πŸ’ͺ 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​

we’ll create a Life Advice App using JSON data and JavaScript. You'll learn how to display random advice with each click, and practice real-world coding skills while making something you can actually use or share.

  • How to fetch and display data from a JSON file

  • How to use arrays and random selection in JavaScript

  • How to build a simple UI with HTML, CSS, and JavaScript

  • How to turn a JSON file into a motivational advice generator


** Step 1: HTML​

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>πŸ’‘ Life Advice App</title>
</head>
<body>
<h1>πŸ’‘ Life Advice App</h1>
<button id="getAdvice">Get Advice</button>
<p id="advice">Click the button to receive wisdom πŸ’¬</p>

<script src="script.js"></script>
</body>
</html>

Step 2: JS​

// 🧠 Step 1: Create sample JSON data in JavaScript
const adviceList = [
{ id: 1, advice: "Believe in yourself. You're braver than you think!" },
{ id: 2, advice: "Small steps every day lead to big results." },
{ id: 3, advice: "Your mindset is your superpower. Use it wisely." },
{ id: 4, advice: "Don't be afraid to start over. It’s a new opportunity!" },
{ id: 5, advice: "Gratitude turns what we have into enough." }
];

// 🌟 Step 2: Get DOM elements
const adviceBtn = document.getElementById("getAdvice");
const adviceText = document.getElementById("advice");

// 🎯 Step 3: Add click event to button
adviceBtn.addEventListener("click", showRandomAdvice);

// πŸš€ Step 4: Function to pick and display random advice
function showRandomAdvice() {
const randomIndex = Math.floor(Math.random() * adviceList.length); // Pick random index
const randomAdvice = adviceList[randomIndex]; // Get that advice object
adviceText.textContent = `πŸ’¬ "${randomAdvice.advice}"`; // Show advice
}