DEV Community

Cover image for Random Quote Generator Using HTML, CSS, and JavaScript
Neha Soni
Neha Soni

Posted on

Random Quote Generator Using HTML, CSS, and JavaScript

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>
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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

getNewQuote();
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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.

See you in my next Blog article, Take care!!

Happy Learning๐Ÿ˜ƒ๐Ÿ˜ƒ

Top comments (10)

Collapse
 
rajeshkumaryadavdotcom profile image
RajeshKumarYadav.com • Edited

How your code so so colourful on dev.to code panel while my ones are black and white?

How did you write your code? Did you use 3 backtick then code then 3 backtick?

Collapse
 
nehasoni__ profile image
Neha Soni • Edited

Add the type of file after your opening backticks for syntax highlighting.

Collapse
 
rajeshkumaryadavdotcom profile image
RajeshKumarYadav.com

wow that worked, thank you so much - tons of hearts :)

Collapse
 
rajeshkumaryadavdotcom profile image
RajeshKumarYadav.com

This is good article for beginners to play with and thanks for sharing live demo link as well.

Keep it up, happy coding!

Collapse
 
nehasoni__ profile image
Neha Soni

Thank you๐Ÿ˜Š๐Ÿค

Collapse
 
siqnax profile image
siqnax

Hi, how can I fetch quotes from my own JSON file

Collapse
 
atulcodex profile image
๐Ÿšฉ Atul Prajapati ๐Ÿ‡ฎ๐Ÿ‡ณ

Hey neha, do you learning js from freecodecamp? Because this project is also available in freecodecamp project

Collapse
 
siqnax profile image
siqnax

Hi,
How can I fetch quotes from my own json? Kindly help

Collapse
 
nehasoni__ profile image
Neha Soni

Please refer to this link:- codepen.io/dudleystorey/pen/ORKWoE

Collapse
 
nikhilghumare3 profile image
Nikhil Ghumare

Mam please share The PPT of this project