MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Mini Project: Random Joke Generator0%
Study Materials
JavaScript for IntermediateProgress 0%
1.1Block Scope with let & const1.2Template Literals1.3Destructuring Arrays and Objects1.4Default Parameters1.5Enhanced Object Literals
8.1Fetching Data from APIs8.2Handling JSON Responses8.3GET vs POST Requests8.4Mini Project: Random Joke Generator
HomeTutorialsJavaScript for IntermediateMini Project: Random Joke Generator
try...catch

Mini Project: Random Joke Generator

Beginner12 min read•Updated: 2026-09-15•By Er. Sumit Kumar (MSK Institute)
Study Materials

In this hands-on project, you will build a complete, interactive Random Joke Generator from scratch. This project brings together everything covered in this module: DOM selection, dynamic element creation, event listeners, async/await, the Fetch API, JSON parsing, and error handling with visual loading states.


1. Project Specifications

  1. 1
    Fetch from Public API: Connect to the Official Joke API or JokeAPI.
  2. 2
    Interactive UI: A button triggers an asynchronous fetch for a new punchline.
  3. 3
    Stateful Loading Indicator: Disable button and show a spinner while the network request is pending.
  4. 4
    Resilient Error Handling: Display a user-friendly error card if the network fails.
  5. 5
    Two-Part Punchline Animation: Display the setup first, followed by a slight delay or reveal button for the punchline.

2. Project Architecture & HTML Structure

1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8" />
5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6 <title>Developer Joke Generator</title>
7 <link rel="stylesheet" href="style.css" />
8</head>
9<body>
10 <main class="card">
11 <header class="card-header">
12 <span class="badge">JavaScript Fetch API</span>
13 <h1>Tech Humour Generator</h1>
14 </header>
15 
16 <div class="content-area">
17 <div id="loader" class="spinner hidden"></div>
18 <p id="joke-setup" class="setup">Click below to generate a fresh joke!</p>
19 <p id="joke-delivery" class="delivery hidden"></p>
20 <div id="error-message" class="error hidden"></div>
21 </div>
22 
23 <footer class="card-actions">
24 <button id="btn-reveal" class="btn btn-secondary hidden">Reveal Punchline</button>
25 <button id="btn-next" class="btn btn-primary">Get New Joke</button>
26 </footer>
27 </main>
28 
29 <script src="app.js"></script>
30</body>
31</html>

3. Styling the Interface (style.css)

1:root {
2 --primary: #6366f1;
3 --primary-hover: #4f46e5;
4 --bg-dark: #0f172a;
5 --surface: #1e293b;
6 --text-main: #f8fafc;
7 --text-muted: #94a3b8;
8 --accent: #10b981;
9 --danger: #ef4444;
10}
11 
12body {
13 font-family: system-ui, -apple-system, sans-serif;
14 background-color: var(--bg-dark);
15 color: var(--text-main);
16 min-height: 100vh;
17 display: flex;
18 align-items: center;
19 justify-content: center;
20 margin: 0;
21 padding: 1rem;
22}
23 
24.card {
25 background: var(--surface);
26 border-radius: 1rem;
27 padding: 2rem;
28 max-width: 500px;
29 width: 100%;
30 box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.5);
31 display: flex;
32 flex-direction: column;
33 gap: 1.5rem;
34}
35 
36.badge {
37 background: rgba(99, 102, 241, 0.15);
38 color: var(--primary);
39 padding: 0.25rem 0.75rem;
40 border-radius: 9999px;
41 font-size: 0.8rem;
42 font-weight: 600;
43}
44 
45.setup {
46 font-size: 1.25rem;
47 font-weight: 600;
48 line-height: 1.5;
49}
50 
51.delivery {
52 font-size: 1.1rem;
53 color: var(--accent);
54 font-weight: 500;
55 margin-top: 1rem;
56 padding: 0.75rem;
57 background: rgba(16, 185, 129, 0.1);
58 border-left: 4px solid var(--accent);
59 border-radius: 0.25rem;
60}
61 
62.error {
63 color: var(--danger);
64 background: rgba(239, 68, 68, 0.1);
65 padding: 0.75rem;
66 border-radius: 0.5rem;
67 font-size: 0.9rem;
68}
69 
70.btn {
71 cursor: pointer;
72 padding: 0.75rem 1.5rem;
73 border-radius: 0.5rem;
74 font-weight: 600;
75 border: none;
76 transition: background 0.2s;
77}
78 
79.btn-primary { background: var(--primary); color: white; }
80.btn-primary:hover { background: var(--primary-hover); }
81.btn-primary:disabled { opacity: 0.6; cursor: not-allowed; }
82 
83.btn-secondary { background: #334155; color: white; margin-right: 0.5rem; }
84.hidden { display: none !important; }

4. Application Logic (app.js)

1// DOM Element References
2const setupEl = document.querySelector('#joke-setup');
3const deliveryEl = document.querySelector('#joke-delivery');
4const errorEl = document.querySelector('#error-message');
5const loaderEl = document.querySelector('#loader');
6const nextBtn = document.querySelector('#btn-next');
7const revealBtn = document.querySelector('#btn-reveal');
8 
9// State
10let currentDelivery = '';
11 
12// Toggle loading states
13function setLoading(isLoading) {
14 nextBtn.disabled = isLoading;
15 if (isLoading) {
16 loaderEl.classList.remove('hidden');
17 errorEl.classList.add('hidden');
18 revealBtn.classList.add('hidden');
19 deliveryEl.classList.add('hidden');
20 } else {
21 loaderEl.classList.add('hidden');
22 }
23}
24 
25// Fetch random joke from API
26async function fetchJoke() {
27 setLoading(true);
28 try {
29 const API_URL = 'https://v2.jokeapi.dev/joke/Programming?blacklistFlags=nsfw,religious,political,racist,sexist';
30
31 // Timeout after 6 seconds
32 const response = await fetch(API_URL, {
33 signal: AbortSignal.timeout(6000)
34 });
35 
36 if (!response.ok) {
37 throw new Error(`Server returned status ${response.status}`);
38 }
39 
40 const data = await response.json();
41 
42 if (data.error) {
43 throw new Error(data.message || 'API reported an error');
44 }
45 
46 // Process single-part vs two-part joke
47 if (data.type === 'single') {
48 setupEl.textContent = data.joke;
49 deliveryEl.classList.add('hidden');
50 revealBtn.classList.add('hidden');
51 } else {
52 setupEl.textContent = data.setup;
53 currentDelivery = data.delivery;
54 deliveryEl.textContent = data.delivery;
55 deliveryEl.classList.add('hidden');
56 revealBtn.classList.remove('hidden');
57 }
58 } catch (err) {
59 setupEl.textContent = 'Oops! Something went wrong.';
60 errorEl.textContent = `Error: ${err.message}. Please check your connection and try again.`;
61 errorEl.classList.remove('hidden');
62 } finally {
63 setLoading(false);
64 }
65}
66 
67// Reveal punchline handler
68revealBtn.addEventListener('click', () => {
69 deliveryEl.classList.remove('hidden');
70 revealBtn.classList.add('hidden');
71});
72 
73// Next joke handler
74nextBtn.addEventListener('click', fetchJoke);

5. Architectural Takeaways

  1. 1
    State Isolation: setLoading(boolean) centralizes UI updates (buttons, spinners, visibility) so state never gets out of sync.
  2. 2
    Network Resilience: Combining response.ok, try/catch, and AbortSignal.timeout(6000) ensures the app never hangs indefinitely.
  3. 3
    Graceful Degradation: Both single-part jokes and two-part setup/delivery jokes are handled smoothly.

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
Why is nextBtn.disabled set to true during fetchJoke()?
Question 2
Why is setLoading(false) placed in the finally block?
Question 3
What happens in app.js if the API returns a 'two-part' joke?
Question 4
How does this project handle slow network connections that hang indefinitely?
Question 5
What is the primary role of the class hidden (display: none !important) in this project?
Next Lesson

try...catch

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
GET vs POST Requeststry...catch

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext