Learn How to Create Quote Generator using HTML, CSS, and JavaScript

Faraz

By Faraz -

Learn how to create a modern quote generator with HTML, CSS, and JavaScript. A step-by-step guide with examples and tips to tweet quotes.


learn-how-to-create-quote-generator-using-html-css-and-javascript.webp

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Conclusion
  6. Preview

Are you ready to enhance your front-end web development skills? A quote generator using HTML, CSS, and JavaScript is a great beginner project. It teaches how to manipulate DOM elements, style the page with CSS, and use JavaScript functions to generate random results. The project is simple yet useful, and it offers a lot of room for creativity, such as share features.

Before diving into the tutorial, make sure you have some basic understanding of HTML, CSS, and JavaScript.

Prerequisites

  • Basic knowledge of HTML structure (e.g., tags, elements).
  • Familiarity with CSS styling (fonts, layout, and alignment).
  • Understanding of JavaScript functions and events.
  • A text editor like VS Code or Sublime Text.
  • A browser to test your project (e.g., Chrome or Firefox).

Source Code

Step 1 (HTML Code):

Create a new HTML file named index.html. The HTML part holds the structure of the quote generator, such as the quote text, author name, and buttons.

Let's break down the HTML code step by step:

<!DOCTYPE html>
<html lang="en">
  • <!DOCTYPE html>: Declares the document as HTML5, ensuring the browser renders the content correctly.
  • <html lang="en">: Sets the language of the document to English, helping search engines and accessibility tools understand the content.

Head Section

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Quote Generator using HTML, CSS, and JavaScript</title>
  1. <meta charset="UTF-8">: Specifies the character encoding, allowing the webpage to support special characters and symbols.
  2. <meta name="viewport" content="width=device-width, initial-scale=1.0">: Ensures the page is responsive on all devices, setting the width to match the screen size.
  3. <title>: Defines the title displayed on the browser tab.

CSS Stylesheets and Fonts

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap">
  <link rel="stylesheet" href="styles.css">
</head>
  • Font Awesome: The <link> tag imports Font Awesome icons for use on the page (in this case, a Twitter icon).
  • Google Fonts: Imports the Poppins font, used for text styling.
  • Custom Stylesheet: The styles.css file contains additional CSS to define the layout and design.

Body Section

<body>
<div class="quote-container">
  <div class="quote-card">
    <p id="quote" class="quote-text">"Click below to generate a new quote!"</p>
    <p id="author" class="quote-author">- Random Author</p>
    <div class="controls">
      <button id="new-quote" class="btn">New Quote</button>
      <a href="#" id="tweet-quote" target="_blank">
        <i class="fab fa-twitter"></i>
      </a>
    </div>
  </div>
</div>
  • <div class="quote-container">: A wrapper for the entire quote section.
  • <div class="quote-card">: A smaller container to hold the quote and controls.
  • <p id="quote" class="quote-text">: A paragraph element displaying a default quote.
  • <p id="author" class="quote-author">: Displays the author of the quote.
  • <div class="controls">: Contains buttons for user interaction:
    • "New Quote" Button: Generates a new random quote.
    • Twitter Link with Icon: A link with a Twitter icon from Font Awesome, allowing users to tweet the quote.

JavaScript Libraries and Custom Script

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="script.js"></script>
</body>
</html>
  • jQuery Library: The <script> tag imports jQuery (a popular JavaScript library) to make it easier to manipulate the DOM and handle events.
  • script.js File: The script.js file contains the JavaScript logic for generating and displaying new quotes, as well as the tweet feature.

Step 2 (CSS Code):

Create a new file named styles.css. Use CSS to make your quote generator look clean and modern.

Let's break down the CSS code step by step:

Global Styles

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
  • * Selector: Targets all HTML elements, ensuring consistent styles across browsers.
    • margin: 0; & padding: 0;: Removes any default spacing around elements.
    • box-sizing: border-box;: Ensures padding and borders are included in the element’s width and height, preventing layout issues.
    • font-family: 'Poppins', sans-serif;: Applies the Poppins font to all elements. If unavailable, it falls back to a generic sans-serif font.

Body Styling

body {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(to right, #00c6ff, #0072ff);
  transition: background 0.8s ease;
}
  • height: 100vh;: Makes the body take up the full height of the viewport.
  • display: flex;: Uses Flexbox to align items inside the body.
  • justify-content: center;: Centers the content horizontally.
  • align-items: center;: Centers the content vertically.
  • background: linear-gradient(to right, #00c6ff, #0072ff);: Creates a gradient background transitioning from light blue to dark blue.
  • transition: background 0.8s ease;: Smoothly transitions the background color over 0.8 seconds when changed.

Quote Container

.quote-container {
  width: 400px;
  background: white;
  border-radius: 15px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  animation: fade-in 1s ease-in-out;
}
  • width: 400px;: Sets the container’s width to 400 pixels.
  • background: white;: Makes the background color white.
  • border-radius: 15px;: Rounds the corners of the container.
  • box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);: Adds a subtle shadow, giving the container a floating appearance.
  • overflow: hidden;: Ensures content that overflows the container is hidden.
  • animation: fade-in 1s ease-in-out;: Animates the container's appearance with a fade-in effect.

Quote Card and Text Styling

.quote-card {
  padding: 30px;
  text-align: center;
}

.quote-text {
  font-size: 1.5rem;
  margin-bottom: 15px;
  font-style: italic;
  color: #333;
}

.quote-author {
  font-size: 1rem;
  color: #555;
  margin-bottom: 20px;
}
  • .quote-card: Adds padding and centers the text.
  • .quote-text:
    • font-size: 1.5rem;: Sets the font size to 1.5 times the default.
    • font-style: italic;: Makes the text italicized.
    • color: #333;: A dark gray color for better readability.
  • .quote-author:
    • font-size: 1rem;: Slightly smaller font size for the author name.
    • color: #555;: A lighter gray color.

Controls Section

.controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.btn {
  background: #0072ff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 30px;
  cursor: pointer;
  transition: background 0.3s ease;
}

.btn:hover {
  background: #005fcc;
}

.fab {
  font-size: 1.5rem;
  color: #0072ff;
}
  • .controls:
    • display: flex;: Arranges the child elements in a row.
    • justify-content: space-between;: Distributes the elements evenly with space between them.
  • .btn:
    • background: #0072ff;: A blue background color for the button.
    • padding: 10px 20px;: Adds space inside the button.
    • border-radius: 30px;: Makes the button edges round.
    • cursor: pointer;: Changes the cursor to a pointer when hovering over the button.
    • transition: background 0.3s ease;: Adds a smooth transition when the button’s background changes.
  • .btn:hover: Changes the button’s background to a darker blue when hovered.
  • .fab:
    • Font Awesome Icon Styling: Sets the font size for the Twitter icon to 1.5 times the default and colors it blue.

Keyframes Animation

@keyframes fade-in {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
  • @keyframes fade-in: Defines the fade-in animation.
    • from: Starts with 0 opacity (invisible) and moves the element slightly up by 20px.
    • to: Ends with full opacity and no vertical shift.
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}

body {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(to right, #00c6ff, #0072ff);
  transition: background 0.8s ease;
}

.quote-container {
  width: 400px;
  background: white;
  border-radius: 15px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  animation: fade-in 1s ease-in-out;
}

.quote-card {
  padding: 30px;
  text-align: center;
}

.quote-text {
  font-size: 1.5rem;
  margin-bottom: 15px;
  font-style: italic;
  color: #333;
}

.quote-author {
  font-size: 1rem;
  color: #555;
  margin-bottom: 20px;
}

.controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.btn {
  background: #0072ff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 30px;
  cursor: pointer;
  transition: background 0.3s ease;
}

.btn:hover {
  background: #005fcc;
}

.fab {
  font-size: 1.5rem;
  color: #0072ff;
}

@keyframes fade-in {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
} 

Step 3 (JavaScript Code):

Create a new file called script.js. This JavaScript file will contain the logic to randomly display quotes.

Let's break down the JavaScript code step by step:

jQuery Document Ready

$(document).ready(function () {
  • $(document).ready(function () {...}): This is a jQuery method that ensures the DOM is fully loaded before executing any JavaScript code inside the function. It prevents the code from running before the HTML elements are available.

Quotes Array

const quotes = [
  { text: "The only way to do great work is to love what you do.", author: "Steve Jobs" },
  { text: "Success is not final, failure is not fatal: It is the courage to continue that counts.", author: "Winston Churchill" },
  ...
];
  • const quotes = [...]: This declares a constant array named quotes containing several quote objects. Each object has two properties:
    • text: The actual quote.
    • author: The name of the person who said the quote.

Random Quote Function

function getRandomQuote() {
  const randomIndex = Math.floor(Math.random() * quotes.length);
  const quote = quotes[randomIndex];
  $("#quote").text(`"${quote.text}"`);
  $("#author").text(`- ${quote.author}`);
}
  • function getRandomQuote() {...}: This function generates and displays a random quote.
    • Math.random(): Generates a random number between 0 and 1.
    • Math.floor(...): Rounds down the result to get a valid index for the quotes array.
    • $("#quote").text(...): Uses jQuery to update the HTML element with ID quote with the text of the selected quote, wrapped in quotation marks.
    • $("#author").text(...): Updates the element with ID author to display the author’s name.

Event Listeners

$("#new-quote").click(getRandomQuote);
getRandomQuote();
  • $("#new-quote").click(getRandomQuote);: Attaches a click event listener to the button with ID new-quote. When clicked, it calls the getRandomQuote function to display a new quote.
  • getRandomQuote();: Calls the function immediately when the page loads to show an initial quote.

Tweet Functionality

$("#tweet-quote").click(function () {
  const quoteText = $(".quote-text").text();
  const quoteAuthor = $(".quote-author").text();
  const tweetURL = `https://twitter.com/intent/tweet?text=${encodeURIComponent(quoteText + " " + quoteAuthor)}`;
  $(this).attr("href", tweetURL);
});
  • $("#tweet-quote").click(function () {...});: Sets up a click event for the element with ID tweet-quote. When clicked:
    • const quoteText = $(".quote-text").text();: Retrieves the current quote text from the element with the class quote-text.
    • const quoteAuthor = $(".quote-author").text();: Retrieves the current author name from the element with the class quote-author.
    • const tweetURL = ...: Constructs a Twitter sharing URL using the retrieved quote and author. The encodeURIComponent(...) function encodes the text for safe inclusion in the URL.
    • $(this).attr("href", tweetURL);: Sets the href attribute of the tweet link to the constructed URL, allowing users to tweet the quote when they click the link.
$(document).ready(function () {
  const quotes = [
    { text: "The only way to do great work is to love what you do.", author: "Steve Jobs" },
    { text: "Success is not final, failure is not fatal: It is the courage to continue that counts.", author: "Winston Churchill" },
    { text: "Believe you can and you're halfway there.", author: "Theodore Roosevelt" },
    { text: "Act as if what you do makes a difference. It does.", author: "William James" },
    { text: "You miss 100% of the shots you don't take.", author: "Wayne Gretzky" },
    { text: "In the middle of every difficulty lies opportunity.", author: "Albert Einstein" },
    { text: "Don’t watch the clock; do what it does. Keep going.", author: "Sam Levenson" },
    { text: "Opportunities don't happen, you create them.", author: "Chris Grosser" },
    { text: "Your time is limited, so don’t waste it living someone else’s life.", author: "Steve Jobs" },
    { text: "I find that the harder I work, the more luck I seem to have.", author: "Thomas Jefferson" },
    { text: "Success usually comes to those who are too busy to be looking for it.", author: "Henry David Thoreau" }
  ];

  function getRandomQuote() {
    const randomIndex = Math.floor(Math.random() * quotes.length);
    const quote = quotes[randomIndex];
    $("#quote").text(`"${quote.text}"`);
    $("#author").text(`- ${quote.author}`);
  }

  $("#new-quote").click(getRandomQuote);
  getRandomQuote(); 

  $("#tweet-quote").click(function () {
    const quoteText = $(".quote-text").text();
    const quoteAuthor = $(".quote-author").text();
    const tweetURL = `https://twitter.com/intent/tweet?text=${encodeURIComponent(
      quoteText + " " + quoteAuthor
    )}`;
    $(this).attr("href", tweetURL);
  });
});

Final Output:

learn-how-to-create-quote-generator-using-html-css-and-javascript.gif

Conclusion:

Creating a quote generator using HTML, CSS, and JavaScript is a simple yet effective way to practice your front-end skills. This project covers the basics of DOM manipulation, styling with CSS, and handling events with JavaScript. You can enhance it further by adding features like sharing on social media or fetching quotes from an API.

This tutorial is an excellent starting point for anyone learning web development, and it can be expanded into more advanced projects.

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺