Building a Random Quotes Generator: A Step-by-Step Guide with Code

Creating a Random Quotes Generator App is a great way to learn coding by building something practical. This guide explains the steps I followed to create the app, including detailed code snippets to help beginners understand the process at the code level. Project Overview The app fetches random quotes using a public API, displays them on the screen, and allows users to copy or share the quotes. We’ll break down the steps to build this app and discuss the logic behind the code. Step 1: Setting Up the HTML Structure The first step is creating the HTML layout for the app. Here’s the basic structure: Random Quotes Generator Random Quotes Generator "Randomness is not the absence of order, but the presence of possibilities." Quote will appear here Author unknown New Quote Credit: Quotes API Built with ♥ from Dev This code defines the structure of the app, including elements to display the quote, buttons to fetch new quotes, and icons for copy and share functionality. Step 2: Handling CORS Issues with a Proxy Server To fetch quotes from an external API, you need to handle CORS (Cross-Origin Resource Sharing). We achieve this using a simple Express.js proxy server. proxy.js: const express = require("express"); const fetch = require("node-fetch"); const cors = require("cors"); const app = express(); // Enable CORS app.use(cors()); // Define a route for proxying API requests app.get("/api/quote", async (req, res) => { try { const response = await fetch("https://qapi.vercel.app/api/random"); const data = await response.json(); res.json(data); } catch (error) { res.status(500).json({ error: "Failed to fetch data from API" }); } }); const PORT = 4000; app.listen(PORT, () => console.log(`Proxy server running on http://localhost:${PORT}`)); This acts as a local proxy to fetch quotes from the API and bypass CORS restrictions. Step 3: Fetching Quotes with JavaScript The app fetches a new quote when the "New Quote" button is clicked. Here’s how the logic works: index.js: const quote = document.querySelector(".quote"); const author = document.querySelector(".author"); async function generateQuote() { const url = 'http://localhost:4000/api/quote'; try { const response = await fetch(url); if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } const result = await response.json(); quote.textContent = result.quote || "No quote available."; author.textContent = result.author || "Author Unknown"; } catch (error) { console.error("Error fetching quote:", error); quote.textContent = "Failed to fetch quote. Try again later."; } } This script fetches data from the proxy server and updates the app’s UI with the fetched quote and author. Step 4: Adding the Copy Feature To enable users to copy quotes, we use the Clipboard API. copyQuote.js: async function copyQuote() { try { let quote = document.querySelector(".quote").textContent; let author = document.querySelector(".author").textContent; await navigator.clipboard.writeText(`${quote} - ${author}`); alert("Content copied to clipboard"); } catch (error) { console.error('Failed to copy:', error); } } When the user clicks the copy icon, the quote and author are copied to the system clipboard. Step 5: Adding the Share Feature The Navigator API allows users to share quotes on WhatsApp. shareQuote.js: async function shareQuote() { let quote = document.querySelector(".quote").textContent; let author = document.querySelector(".author").textContent; const quoteContent = `${quote} - ${author}`; const message = encodeURIComponent(quoteContent); if (window.screen.width

Jan 21, 2025 - 20:18
 0
Building a Random Quotes Generator: A Step-by-Step Guide with Code

Creating a Random Quotes Generator App is a great way to learn coding by building something practical. This guide explains the steps I followed to create the app, including detailed code snippets to help beginners understand the process at the code level.

Project Overview

The app fetches random quotes using a public API, displays them on the screen, and allows users to copy or share the quotes. We’ll break down the steps to build this app and discuss the logic behind the code.

Step 1: Setting Up the HTML Structure

The first step is creating the HTML layout for the app. Here’s the basic structure:


 lang="en">

     charset="UTF-8">
     name="viewport" content="width=device-width, initial-scale=1.0">
    </span>Random Quotes Generator<span class="nt">
     rel="stylesheet" href="styles.css">    


     class="quote-generator">
         class="title">Random Quotes Generator
         class="subheading">"Randomness is not the absence of order, but the presence of possibilities."
         class="quotebox">
             class="quote">Quote will appear here
             class="author">Author unknown
        
class="quote-button" type="button" onclick="generateQuote()">New Quote
class="copyquote" onclick="copyQuote()"> src="images/copy.png" class="icon-style" alt="Copy Icon"> class="sharequote" onclick="shareQuote()"> src="images/share.png" class="icon-style" alt="Share Icon">
class="footer"> class="footer-left"> class="credits" href="https://github.com/theriturajps/Quotes-API" target="_blank" rel="noopener">Credit: Quotes API class="footer-right"> href="https://github.com/theriturajps/Quotes-API" class="menu" target="_blank" rel="noopener"> src="images/dev_github.png" class="icon-style" alt="GitHub Icon"> href="https://github.com/theriturajps/Quotes-API" class="menu" target="_blank" rel="noopener"> src="images/dev_x_twitter.png" class="icon-style" alt="Twitter Icon"> href="https://github.com/theriturajps/Quotes-API" class="menu" target="_blank" rel="noopener"> src="images/dev_linkedin.png" class="icon-style" alt="LinkedIn Icon">
Built with from Dev