Random Quote Generator Using HTML, CSS, and JavaScript

Random Quote Generator Using HTML, CSS, and JavaScript

·

6 min read

Hello learners,
In this article, you will learn how to build a Random Quote Generator using HTML, CSS, JavaScript, and API. This application fetches a new random quote from an API, upon the click of a button, and displays it in the browser. Here’s a screenshot of what the finished application looks like: Screenshot (248).png Let's get started

Prerequisite

  • Basic knowledge of HTML
  • Basic knowledge of CSS
  • Basic knowledge of JavaScript

It's Time to Code!

Our Random quote generator project contains three parts: HTML, CSS, and JavaScript. So first you need to create three files, the first one is HTML File(index.html), the second one is CSS file(style.css) and the third one is JS file(index.js).

HTML Part

Open your index.html file and type the following code inside it.

<!DOCTYPE html>
<html>
    <head>
        <!--META information-->
        <meta charset="UTF-8">
        <meta name="description" content="Random Quote Generator">
        <meta name="keywords" content="HTML,CSS,JavaScript, Quotes, API">
        <meta name="author" content="Neha Soni">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <!--End of META information-->

        <title>Random Quote Generator</title>

        <!--LINK CUSTOM CSS FILE-->
        <link rel="stylesheet" href="style.css">

        <!--FONTAWESOME CDN-->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" integrity="sha512-+4zCK9k+qNFUR5X+cKL9EIR+ZOhtIloNl9GIKS57V1MyNsYpYcUrUeQc9vNfzsWfV28IaLL3i96P9sdNyeRssA==" crossorigin="anonymous" />
    </head>
    <body>
        <!-- Quote Container -->
        <div class="container">
             <!-- Quote to be Displayed Here -->
            <h1>
            <i class="fas fa-quote-left"></i>
            <span class="quote" id="quote"></span>
            <i class="fas fa-quote-right"></i>
            </h1>
            <!-- Author to be Displayed Here -->
            <p class="author" id="author"></p>

            <hr/>
            <div class="buttons">
               <!--Button to tweet the quote -->
                <a class="twitter" id="tweet" href="https://twitter.com/intent/tweet?text=Greetings" data-size="large" target="_blank" rel="noopener noreferrer"><i class="fab fa-twitter"></i></a>

                <!--Add an onclick event on 'next quote' button. Upon the click of a button, a new random quote is generated-->
                <button class="next" onclick="getNewQuote()">Next quote</button>
            </div>
        </div>

        <!--LINK CUSTOM JS FILE-->
        <script src="script.js"></script>
    </body>
</html>

CSS Part

style.css

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

body{
    min-height:100vh;
    transition: 0.5s;
    transition-timing-function: ease-in;
    background-image: linear-gradient(to right bottom, rgb(255, 128, 128), #ffedbca8);
    display: flex;
    align-items: center;
    justify-content: center;

}

.container
{
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 30px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.6);
    border-radius: 15px;
    width: 600px;
    background-color: rgba(255, 255, 255, 0.3);
    margin: 10px;

}
.fa-quote-left, .fa-quote-right {
    font-size: 35px;
    color: rgb(179, 0, 0);
}
.quote
{
    text-align: center;
    font-size: 40px;
    font-weight: bold;
}
.author 
{

    margin:10px;
    text-align: right;
    font-size: 25px;
    font-style: italic;
    font-family: cursive;
}
hr {
    margin: 10px 0;
    width: 100%;
    border: 1px solid black;
    background-color: black;
}
.buttons {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 9px;
}
.twitter
{
    border:1px solid rgb(102, 179, 255);
    border-radius: 4px;
    background-color: rgb(102, 179, 255);
    color: white;
    text-align: center;
    font-size: 1.8em;
    width: 60px;
    height: 35px;
    line-height: 40px;
}
.next
{
    font-size:18px;
    border-radius: 5px;
    cursor:pointer;
    padding: 10px;
    margin-top: 5px;
    font-weight: bold;
    color: white;
    background-image: linear-gradient(to right bottom, rgb(230, 0, 0), #ffedbca8);
}
.container:hover
{
    box-shadow: 0 10px 10px rgb(230, 0, 0);
}

JavaScript Part

Now here comes the main and last part of our random quote generator app. The entire code for the working of the app is written within the getNewQuote() function. In this function, we will fetch the data from the API. Since fetching the data from API is an asynchronous process so we will use the async function to fetch the data and store it in the array. Learn more about JavaScript async function here.

Let's discuss everything step by step:-
Step 1:- Create a function getNewQuote().

const getNewQuote = async () =>
{
  //code to be executed
}

Step 2:- Store the API in an url variable and fetch the data from it using fetch() method. Now the fetch() method returns a promise, to handle it we use await keyword. Whenever the promise gets resolved save the data in the response variable.

const getNewQuote = async () =>
{
    //api for quotes
    var url="https://type.fit/api/quotes";    

    // fetch the data from api
    const response=await fetch(url);
}

Step 3:- Convert the response to JSON format and it also returns a promise so again we need to add await keyword to handle the promise and whenever the promise gets resolved we will save the data in the allQuotes array.

    const allQuotes = await response.json();

Step 4:- JavaScript has useful built-in functions: Math.floor() and Math.random(). We will use Math.random() method to generate a number between 0 and a total number of quotes fetched from the API(length of allQuotes array) and Math.floor() method to rounds a number DOWNWARDS to the nearest integer. Now, with the help of this number, we will be able to access a single object from an array.

 const indx = Math.floor(Math.random()*allQuotes.length);

Step 5:- Each element stored in the array is an object which has the property text and author. Store the quote present at the randomly generated index and also store the author of the respective quote.

const quote=allQuotes[indx].text;
const auth=allQuotes[indx].author;

Step 6:- Making the author anonymous if no author is present and once the values are ready, let's display it in the HTML elements which we made before. This is done by obtaining them using the document.getElementById method and insert the values inside it using the innerHTML property.

if(auth==null)
{
     author = "Anonymous";
}

const text=document.getElementById("quote");
const author=document.getElementById("author");

text.innerHTML=quote;
author.innerHTML="~ "+auth;

Step 7:- Add some attribute to the Twitter button to tweet the quote with the following code:

const tweetButton=document.getElementById("tweet");
tweetButton.href="https://twitter.com/intent/tweet?text="+quote+" ~ "+auth;

Step 8:- Call the function getNewQuote() at the end to start function at exact reloading of the page.

getNewQuote();

Complete javascript code
index.js

const text=document.getElementById("quote");
const author=document.getElementById("author");
const tweetButton=document.getElementById("tweet");

const getNewQuote = async () =>
{
    //api for quotes
    var url="https://type.fit/api/quotes";    

    // fetch the data from api
    const response=await fetch(url);
    console.log(typeof response);
    //convert response to json and store it in quotes array
    const allQuotes = await response.json();

    // Generates a random number between 0 and the length of the quotes array
    const indx = Math.floor(Math.random()*allQuotes.length);

    //Store the quote present at the randomly generated index
    const quote=allQuotes[indx].text;

    //Store the author of the respective quote
    const auth=allQuotes[indx].author;

    if(auth==null)
    {
        author = "Anonymous";
    }

    //function to dynamically display the quote and the author
    text.innerHTML=quote;
    author.innerHTML="~ "+auth;

    //tweet the quote
    tweetButton.href="https://twitter.com/intent/tweet?text="+quote+" ~ "+auth;
}
getNewQuote();

congrats.gif You have just created a random quote generator. It will look something like this! quoteGeneratorGIF.gif

If you enjoyed learning and find it useful please do like and share so that, it reaches others as well 🤝

Thanks for reading 😃

I would ❤ to connect with you at Twitter | LinkedIn | GitHub

Let me know in the comment section if you have any doubt or feedback.

You should definitely check out my other Blogs:

See you in my next Blog article, Take care!!
Happy Learning😃😃

Did you find this article valuable?

Support Neha Soni's Blog by becoming a sponsor. Any amount is appreciated!