Random Quote Generator Using HTML, CSS, and JavaScript
Tags: javascript, webdev, html, css
Published: 2021-05-23 06:45:00

Hello learners,<br>
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](https://cdn.hashnode.com/res/hashnode/image/upload/v1620373273308/WsJWtYo7f.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.
```html
<!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*
```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](https://www.w3schools.com/js/js_async.asp) here.*

Let's discuss everything step by step:-<br>
**Step 1:**- Create a function getNewQuote().
```js
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.
```js
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.
```js
    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.
```js
 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.
```js
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. 
```js
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:
```js
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.
```js
getNewQuote();
```
**Complete javascript code**<br>
index.js
```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](https://cdn.hashnode.com/res/hashnode/image/upload/v1620379570034/SROaYCdi8.gif)
**You have just created a random quote generator. It will look something like this!**
![quoteGeneratorGIF.gif](https://cdn.hashnode.com/res/hashnode/image/upload/v1620391069350/Bx53HiNSj.gif)

- [Live Demo](https://nehasoni05.github.io/Random_Quote_Generator/) 
- You can find the code at my  [GitHub Repository](https://github.com/nehasoni05/Random_Quote_Generator) 

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](https://twitter.com/nehasoni__)  |  [LinkedIn](https://www.linkedin.com/in/neha-soni-70a6231b1/) | [GitHub](https://github.com/nehasoni05)

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

See you in my next Blog article, Take care!!<br>
**Happy Learning😃😃**