DEV Community

Cover image for Day-6 of Learning JavaScript: The Zen of Quotes: A Beginner’s Guide to Crafting a Random Quote Generator
Aniket Saini
Aniket Saini

Posted on

Day-6 of Learning JavaScript: The Zen of Quotes: A Beginner’s Guide to Crafting a Random Quote Generator

Ever stare at a blank page, yearning for inspiration? Or perhaps you crave a daily dose of wisdom to kickstart your day. If so, buckle up, fellow word lovers, because today we’re building a Random Quote Generator!

Imagine this: a webpage adorned with a captivating quote, changing like a whimsical kaleidoscope with each refresh or button click. Sounds fancy, right? But trust me, creating this literary gem is easier than baking a souffle (and infinitely less messy!).

What is a Random Quote Generator?

A random quote generator is a webpage that displays a random quote from a collection of quotes each time it is loaded or when a button is clicked. The quotes can be inspirational, motivational, humorous, or anything else that you like. The random quote generator can also display the author of the quote, or the source of the quote, if available.

Our Toolkit:

To craft this quote-slinging machine, we’ll need HTML, CSS, and JavaScript. Don’t panic if these acronyms sound like alien alphabets; we’ll decipher them together, step-by-step.


1. HTML: The Blueprint:

Think of HTML as the foundation of our webpage. It tells the browser where to put everything, like a quote, a button, and maybe a dancing hamster GIF (because why not?).

The HTML part of the random quote generator is very simple. You just need to create a <div> element that will contain the quote and the author, and a <button> element that will trigger the random quote generation. You can also add a <title> element to give your webpage a name, and a <style> element to link your CSS file.

Here is an example of the HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Random Quote Generator</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div id="quote-container">
        <p id="quote">"The only thing we have to fear is fear itself."</p>
        <p id="author">- Franklin D. Roosevelt</p>
    </div>
    <button id="new-quote">New Quote</button>
    <img src="https://media.tenor.com/Z5tmG7qYS44AAAAi/shishiro-botan-botan.gif">
    <script src="script.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In Plain English:

  • We declare the document type and language.

  • We set the title to our quote generator name.

  • We link to a CSS file for styling (coming soon!).

  • We create headings and a paragraph element with an ID “quote” where the quotes will appear.

  • We add a button with an onclick event that triggers the “generateQuote” function (written in JavaScript, just waiting for its cue!).

  • Finally, we link to the JavaScript file containing the magic code.


2. CSS: The Stylist:

The CSS part of the random quote generator is where you can customize the look and feel of your webpage. You can change the font, color, size, alignment, margin, padding, border, background, and other properties of the elements. You can also add some transitions or animations to make your webpage more dynamic and attractive.

Here is an example of the CSS code:

* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

body {
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
}

#quote-container {
    max-width: 800px;
    text-align: center;
    background-color: white;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

#quote {
    font-size: 24px;
    font-style: italic;
    color: #333;
}

#author {
    font-size: 18px;
    font-weight: bold;
    color: #555;
    margin-top: 10px;
}

#new-quote {
    font-size: 16px;
    font-weight: bold;
    color: white;
    background-color: #333;
    padding: 10px 20px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    margin-top: 20px;
    transition: background-color 0.3s;
}

#new-quote:hover {
    background-color: #555;
}
Enter fullscreen mode Exit fullscreen mode

In Plain English:

  • We set the font family, alignment, and padding for different elements.

  • We make the quote big and bold, and the button inviting to click.

  • Now, the real fun begins! We define an animation class “spin” and a keyframe animation “spin” to rotate our dancing hamster (remember, it’s optional, but highly recommended!)


3. JavaScript: The Brain of the Operation:

The JavaScript part of the random quote generator is where you add the logic and functionality to your webpage. You will need to create an array that stores the quotes and the authors, and a function that selects and displays a random quote from the array. You will also need to add an event listener that calls the function when the button is clicked.

Here is an example of the JavaScript code:

// Create an array that stores the quotes and the authors
var quotes = [
    {
        quote: "The only thing we have to fear is fear itself.",
        author: "Franklin D. Roosevelt"
    },
    {
        quote: "Be the change that you wish to see in the world.",
        author: "Mahatma Gandhi"
    },
    {
        quote: "Don't cry because it's over, smile because it happened.",
        author: "Dr. Seuss"
    },
    {
        quote: "You only live once, but if you do it right, once is enough.",
        author: "Mae West"
    },
    {
        quote: "Be yourself; everyone else is already taken.",
        author: "Oscar Wilde"
    }
];

// Get the elements from the HTML document
var quoteContainer = document.getElementById("quote-container");
var quote = document.getElementById("quote");
var author = document.getElementById("author");
var newQuote = document.getElementById("new-quote");

// Create a function that selects and displays a random quote from the array
function displayRandomQuote() {
    // Get a random index from the array
    var randomIndex = Math.floor(Math.random() * quotes.length);
    // Get the quote and the author from the array
    var randomQuote = quotes[randomIndex].quote;
    var randomAuthor = quotes[randomIndex].author;
    // Display the quote and the author in the HTML elements
    quote.textContent = '"' + randomQuote + '"';
    author.textContent = '- ' + randomAuthor;
}

// Add an event listener that calls the function when the button is clicked
newQuote.addEventListener("click", displayRandomQuote);

Enter fullscreen mode Exit fullscreen mode

Here’s a plain English explanation of the code:

1. Storing Treasure Chests of Wisdom:

  • We create a big box named “quotes” to house our inspiring quotes and their authors.

  • Each quote is like a mini-treasure chest, holding the quote itself and the person who said it.

2. Finding the Right Spots on the Page:

  • We imagine the webpage as a house with rooms and furniture.

  • We use special tools to find the specific rooms where we’ll display the quotes (a room called “quote-container”), the quote itself (a box named “quote”), the author (a nameplate called “author”), and a button to trigger a new quote (a fancy doorknob called “new-quote”).

3. Unveiling Random Gems:

  • We create a clever helper named “displayRandomQuote” who does a few things:

  • It closes its eyes and points randomly at one of the treasure chests in the “quotes” box.

  • It carefully opens that chest and pulls out the quote and author inside.

  • It proudly displays the quote in the “quote” box and the author’s name on the “author” nameplate.

4. Making the Button Magic:

  • We attach a special listening device to the “new-quote” doorknob.

  • Whenever someone clicks that doorknob, it calls upon our trusty helper “displayRandomQuote” to reveal a new gem of wisdom.


JavaScript Concepts We Learned:

  • Arrays: Like boxes for storing collections of things, each with a number tag for easy access.

  • Objects: Like mini-treasure chests, holding pairs of information (like a quote and its author).

  • Variables: Like labels for storing different types of data, from simple words to entire treasure chests.

  • Document Object Model (DOM): Like a map of our webpage, helping us find specific rooms and furniture to interact with.

  • Functions: Like helpful workers who perform specific tasks when called upon.

  • Event Listeners: Like listening devices that activate functions when certain events happen, like a button click.

  • Math.random(): Like a magic dice that rolls numbers between 0 and 1, helping us pick random items from a collection.

  • textContent: Like a way to fill boxes with text, changing what’s displayed on the webpage.

The Grand Finale: A Webpage That Talks

Open your HTML file in a web browser, and voila! You now have a webpage that dispenses wisdom with every click of the “Summon Wisdom” button. Each click reveals a new quote, creating a digital oracle that speaks to you.

CLICK HERE to check the Final Output.

Epilogue: Your Coding Odyssey Continues

Congratulations, dear coder! You’ve just embarked on a coding odyssey that introduced you to the basics of HTML, CSS, and the enchanting world of JavaScript. This is just the beginning. As you delve deeper into coding, you’ll uncover new spells, tricks, and possibilities.

Remember, the world of coding is vast and exciting. Embrace the challenges, celebrate the victories, and keep coding with a sense of wonder. Happy coding, and may your quotes be forever random and enlightening! 😊

Top comments (0)