Projects

Building a Random Quote Generator with JavaScript

Introduction to the Random Quote Generator

Welcome to the beginner-friendly tutorial on building a Random Quote Generator with JavaScript! In this project, we'll create a simple app that fetches random quotes from an API and displays them dynamically. This project is an excellent way to learn API integration and UI updates in JavaScript.

Setting Up Your Workspace

Creating Your Project Folder and Files

Before we begin coding, let's set up a workspace for our project. Think of this folder as your digital canvas, where you'll keep all the project files organized.

Step 1: Create Your Project Folder

Create a new folder on your computer to store all your project files. You can name it "random-quote-generator".

On Windows:
  1. Right-click on your desktop.
  2. Choose "New" > "Folder"
  3. Name it "random-quote-generator"
On Mac:
  1. Right-click on your desktop.
  2. Choose "New Folder"
  3. Name it "random-quote-generator"

Step 2: Get Your Text Editor Ready

You'll need a text editor to write your code. We recommend Visual Studio Code, which is free and beginner-friendly.

  1. Download Visual Studio Code from code.visualstudio.com.
  2. Install it on your computer.
  3. Open VS Code and drag your "random-quote-generator" folder into the window.

Step 3: Create Your Project Files

We need three essential files for our project:

To create these files:

  1. Open VS Code.
  2. index.html - Click "New File" and save it as "index.html".
  3. styles.css - Click "New File" again and save it as "styles.css".
  4. script.js - Click "New File" once more and save it as "script.js".

🎯 Success Check: You should now have:

👉 Tip: If something's not working, try restarting VS Code or creating the files using the "File → New File" menu.

Setting Up the HTML Structure

Creating the Quote Generator HTML

Let's start by building the HTML structure for our random quote generator. HTML is like the foundation of our app.

  1. 1. Open "index.html": Open your "index.html" file in your code editor.
  2. 2. Add the Quote Generator HTML: Copy and paste the following code into your "index.html" file:
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Random Quote Generator</title>
      <link rel="stylesheet" href="styles.css">
    </head>
    <body>
      <div class="container">
        <h1>Random Quote Generator</h1>
        <div class="quote-container">
          <p id="quote">Click the button to get a random quote.</p>
          <button id="get-quote">Get Quote</button>
        </div>
      </div>
      <script src="script.js"></script>
    </body>
    </html>

Let's break down the HTML structure:

Save your "index.html" file. Now we have the basic HTML structure in place. In the next step, we'll add some styling to make it look nice!

Styling the Quote Generator

Adding CSS Styles

CSS is like the paint and brushes we use to make our app visually appealing. Let's add some styles to our random quote generator.

  1. 1. Open "styles.css": Open the "styles.css" file in your code editor.
  2. 2. Add Quote Generator Styles: Copy and paste the following CSS code into your "styles.css" file:
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      background-color: #f4f4f4;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
    }
    
    .container {
      background-color: #fff;
      padding: 20px;
      border-radius: 10px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      width: 400px;
      text-align: center;
    }
    
    h1 {
      margin: 0 0 20px;
      font-size: 1.5rem;
    }
    
    .quote-container {
      margin-top: 20px;
    }
    
    #quote {
      font-size: 1.2rem;
      margin-bottom: 20px;
      text-align: center;
    }
    
    button {
      background-color: #007bff;
      color: #fff;
      border: none;
      padding: 10px 20px;
      border-radius: 5px;
      cursor: pointer;
      font-size: 1rem;
      transition: background-color 0.3s ease;
    }
    
    button:hover {
      background-color: #0056b3;
    }

Let's understand the CSS rules we just added:

Save your "styles.css" file. Now, if you open "index.html" in a web browser, you'll see the styled quote generator.

Adding JavaScript for User Interactions

Handling Form Submission and Adding Tasks

Now, let's add JavaScript to make our app interactive! We'll start by handling user interactions and fetching quotes from the API.

Selecting HTML Elements

First, we need to select the HTML elements we want to work with. We'll select the button and the paragraph element.

  1. 1. Open "script.js": Open the "script.js" file in your code editor.
  2. 2. Selecting Elements: Copy and paste the following JavaScript code into your "script.js" file:
    // Selecting HTML elements
    const getQuoteButton = document.getElementById('get-quote');
    const quoteElement = document.getElementById('quote');

Here, we're using the getElementById method to select the HTML elements with specific IDs.

Handling Button Click

Next, we'll add an event listener to the button to handle the click event. We'll fetch a random quote from the API and update the UI.

  1. 3. Handling Button Click: Copy and paste the following JavaScript code into your "script.js" file:
    // Handling button click
    getQuoteButton.addEventListener('click', () => {
      fetch('https://quotes-api-self.vercel.app/quote')
        .then(response => response.json())
        .then(data => {
          quoteElement.textContent = `${data.quote} - ${data.author}`;
        })
        .catch(error => { console.error('Error fetching quote:', error); });
    });

In this part, we're using the addEventListener method to listen for the 'click' event on the button. We fetch a random quote from the API, update the UI with the quote and author, and handle any errors that might occur during the fetch request.

Putting It All Together

Now, let's put everything together. If you've been following along and pasting the code into your "script.js" file, it should look like this:

// Selecting HTML elements
const getQuoteButton = document.getElementById('get-quote');
const quoteElement = document.getElementById('quote');

// Handling button click
getQuoteButton.addEventListener('click', () => {
  fetch('https://quotes-api-self.vercel.app/quote')
    .then(response => response.json())
    .then(data => {
      quoteElement.textContent = `${data.quote} - ${data.author}`;
    })
    .catch(error => { console.error('Error fetching quote:', error); });
});

Making the Quote Generator Responsive

Making the Quote Generator Responsive

Let's ensure our quote generator looks great on various devices by adding responsive design using CSS media queries.

  1. 1. Open "styles.css": Open the "styles.css" file in your code editor.
  2. 2. Add Responsive Design Styles: Copy and paste the following CSS code into your "styles.css" file:
    @media (max-width: 600px) {
      .container {
        width: 90%;
      }
    
      #quote {
        font-size: 1rem;
      }
    
      button {
        padding: 8px 16px;
        font-size: 0.9rem;
      }
    }

Let's understand the CSS rules we just added:

Save your "styles.css" file. Now, if you resize your browser window or view the quote generator on different devices, you'll see the layout adapt to different screen sizes.

In the next step, we'll add final touches to the quote generator.

Adding Final Touches

Adding Final Touches

Let's add the final touches to our quote generator to ensure it is fully functional and visually appealing.

  1. 1. Open "styles.css": Open the "styles.css" file in your code editor.
  2. 2. Add Final Touches: Copy and paste the following CSS code into your "styles.css" file:
    .container {
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    }
    
    button {
      transition: background-color 0.3s ease, transform 0.3s ease;
    }
    
    button:hover {
      transform: scale(1.05);
    }

Let's understand the CSS rules we just added:

Save your "styles.css" file. Now, if you open "index.html" in a web browser, you'll see the final touches in action.

Congratulations! You've completed the JavaScript project, "Random Quote Generator." You've learned how to create a simple app that fetches random quotes from an API and updates the UI dynamically. You've also learned the basics of API integration and UI updates in JavaScript.

Feel free to continue customizing your quote generator and exploring more JavaScript techniques. Happy coding! 🚀