Skip to main content

Task 19: Build a Random Joke Generator with JavaScript | Fun Beginner Coding Project

Start with Affirmation

  • I declare that I am focused, prepared, and ready to take action today.

  • I declare that I am not afraid of learning new things—my mind is sharp and open.

  • I declare that progress is happening even when it feels slow—every effort counts.

  • I declare that what I start, I will finish with clarity and confidence.

  • I declare that distractions lose their power over me—I choose purpose over noise.

  • I declare that I’m building real skills that will unlock new opportunities for me.

  • I declare that I enjoy the process, and I trust where it’s leading me.

  • I declare that I am consistent, committed, and capable of more than I know.

  • I declare that I show up, level up, and grow up in every task I take on.

💪 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

In this fun and beginner-friendly project, we’ll build a Random Joke Generator using JavaScript, HTML, and a public API. It’s a great way to practice working with APIs, JSON, and DOM manipulation—all while having a few laughs along the way!

  • Fetch random jokes from a joke API

  • Display new jokes with a button click

  • Use async/await and the Fetch API in JavaScript

  • Build a simple but useful web app

Perfect for beginners, students, or anyone looking to build fun coding projects with real functionality.

Tools Used:

  • JavaScript (Vanilla)

  • HTML/CSS

  • Joke API (like Official Joke API or JokeAPI)

** Step 1: HTML

<h1>😂 Random Joke Generator</h1>
<button id="getJoke">Tell Me a Joke!</button>
<p id="jokeSetup"></p>
<p id="jokePunchline" style="font-weight: bold;"></p>

Step 2: JS

// Get elements
const button = document.getElementById('getJoke');
const setup = document.getElementById('jokeSetup');
const punchline = document.getElementById('jokePunchline');

// Add event listener
button.addEventListener('click', fetchJoke);

// Async function to fetch joke
async function fetchJoke() {
try {
const response = await axios.get('https://official-joke-api.appspot.com/random_joke');

const joke = response.data;
setup.textContent = `🧐 ${joke.setup}`;
punchline.textContent = `😂 ${joke.punchline}`;
} catch (error) {
console.error('Error fetching joke:', error);
setup.textContent = "Oops! Couldn't fetch a joke.";
punchline.textContent = "";
}
}