Random Quote Generator Using HTML, CSS and JavaScript

25 Feb, 2021
A Random Quote Generator is capable of pulling quotes randomly from an API, a database, or simply from an array. We will be designing a Random Quote Generator from scratch using HTML, CSS, JavaScript, and type.fit API. The webpage displays a random quote from a collection and upon the click of a button, it randomly generates a new quote. We will first generate the basic HTML Template and style it using CSS before diving deeper into the JavaScript Logic.
Making the Bare Bones Of Our Application: In this section, we will use only HTML and put all the required CDN links.
Step 1 (Adding our Foundation): Link your stylesheet and add other resources required for the project as desired, for instance, we have added additional bootstrap libraries and Google fonts for styling purposes. Our next step is to add the main body tag, where the bare bones of the Random Quote Generator Lie. Below is the code for the above step:
HTML
<head>    <!-- Loading The Bootstrap Library -->    <link rel="stylesheet"           href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"           integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"           crossorigin="anonymous"/>      <!-- Loading Icons From Font Awesome -->    <link rel="stylesheet"           href="https://use.fontawesome.com/releases/v5.8.1/css/all.css"           integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf"           crossorigin="anonymous">      <!-- Linking Your CSS File -->    <link rel="stylesheet" href="style.css"/>      <!-- Loading Roboto Font from Google Fonts -->    <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap"           rel="stylesheet">      <!-- Loading Open Sans Font from Google Fonts -->    <link href="https://fonts.googleapis.com/css2?family=Open+Sans+Condensed:wght@300&display=swap"           rel="stylesheet">    </head>
Step 2 (Holding the front part and the back part of the Quote Box): Now it’s time for adding the main HTML Code of our application. Add a div tag that holds the front side and the backside of the Quote Box.
Step 3 (Adding front part of the Quote Box): Add a div element that holds the text, author, and the clickable button.
Step 4 (Allocating area for displaying the quote): Let’s add a span element that holds the left font awesome quote icon and the quote to be displayed. A span tag is used as the quote icon and the quote needs to be on the same line.
Step 5 (Allocating area for displaying the author): Use a div tag to hold the author of the quote.
Step 6 (Adding the button): Use an anchor tag to display the button.
Step 7(Adding the back part of the Quote Box): Repeat the above 5 steps and generate a replica of the quote box which exists behind the current box. After performing the above steps, we have a bare-bones application with no styling or logic.
Below is the entire HTML code generated by following the above steps:
HTML
<!DOCTYPE html><html>  <head>    <!-- Loading The Bootstrap Library -->    <link rel="stylesheet"           href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"           integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"           crossorigin="anonymous"/>      <!-- Loading Icons From Font Awesome -->    <link rel="stylesheet"           href="https://use.fontawesome.com/releases/v5.8.1/css/all.css"           integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf"           crossorigin="anonymous">      <!-- Linking Your CSS File -->    <link rel="stylesheet" href="style.css"/>      <!-- Loading Roboto Font from Google Fonts -->    <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap"           rel="stylesheet">      <!-- Loading Open Sans Font from Google Fonts -->    <link href="https://fonts.googleapis.com/css2?family=Open+Sans+Condensed:wght@300&display=swap"           rel="stylesheet">      </head>    <body id="body">    <div>      <!-- Quote Box -->    <div class="block text-center">        <!-- Front part of the Quote Box -->    <div class = "quote-box block__main block__front">        <!-- Quote to be Displayed Here -->      <span class = "quote">                  <!-- Hyphen is Displayed  -->        <i class="fas fa-2x fa-quote-left"></i>          <!-- Quote Text -->        <span class = "text">        Quote To be Displayed Here        </span>        </span>              <!-- Author to be Displayed Here -->      <div class = "author">        Author to be Displayed Here      </div>      <a  class = "new-quote btn btn-default"           onclick="newQuote()">New Quote</a>    </div>      <!-- Back Part of the Quote Box -->    <div class = "quote-box block__main block__back">        <!-- Quote to be Displayed Here -->      <span class = "quote">                  <!-- Hyphen is Displayed  -->        <i class="fas fa-2x fa-quote-left"></i>          <!-- Quote Text -->        <span class = "text">        Quote To be Displayed Here        </span>        </span>              <!-- Author to be Displayed Here -->      <div class = "author">        Author to be Displayed Here      </div>        <!-- Button -->        <a  class = "new-quote btn btn-default "             onclick="newQuote()">New Quote</a>    </div>  </div></div>      <!-- Linking Your JavaScript File -->  <script src="script.js"></script>  </body>    </html>
Styling The Application: CSS is used to make the application attractive and visually appealing to the end-user.
Center the quote box using the top and left properties.
Apply padding and margin to the necessary elements.
Use two font families, Primary for the quote and Secondary for the author.
Two classes namely rotateB and rotateF are added to rotate the backside and the front side when the button is clicked.
CSS Styling is solely based on the designer’s perspective. We highly recommend you tinker with the code and try out your design.
Below is the CSS code for Reference: 
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, #ed4264a8, #ffedbca8);  }      .quote-box{    padding:3rem;    transition: 0.5s;    transition-timing-function: ease-in;  }      .text{    font-size:30px;    padding-left:10px;    transition: 0.5s;    transition-timing-function: ease-in;    font-family: 'Roboto', sans-serif;    background-image: linear-gradient(to right bottom, #ed4264a8, #ffedbca8);    color: transparent;    -webkit-background-clip: text;  }    .quote{    transition: 0.5s;    transition-timing-function: ease-in;  }    .new-quote{      font-size:15px;      border-radius: 5px;      cursor:pointer;      padding-bottom: 8px;      padding-top: 9px;      margin-top: 5px;      background-image: linear-gradient(to right bottom, #ed4264a8, #ffedbca8);  }    .text-center{    text-align: center;  }      .new-quote:hover{    opacity: 0.6;}    .author{    margin:10px;    font-size:20px;    transition: 0.5s;    transition-timing-function: ease-in;    font-family: 'Open Sans Condensed', sans-serif;    background-image: linear-gradient(to right bottom, #28313B,#485461    );    color: transparent;    -webkit-background-clip: text;  }        p{    margin-top: 5px;    text-align: center;    position: absolute;    width: 100%;    top:21.5%;}  .block {  perspective: 150rem;  position: absolute;  top:25%;  left: 27%;}  .block__main {    min-width: 45vw;    position: absolute;    transition: all .8s ease;    backface-visibility: hidden;    box-shadow: 0rem 1.5rem 4rem rgba(0, 0, 0, 0.15);    border-radius: .5rem;     background-image: linear-gradient(to right bottom, #F6F0EA,#F1DFD1);  }    .block__back {    transform: rotateY(180deg);   }  .rotateF{  transform: rotateY(-180deg);}  .rotateB{  transform: rotate(0deg);}
Upon successful execution of the above steps, we should have an application designed like this :
The logic of the Application: In this section, we will apply all the logics.
Step 1 (Initializing the data array): 
Here we have used an array to store the quotes fetched from the API.
Step 2 (Creating a function to display the quote):
We have created a function named displayQuote which displays the quote when the application is loaded or when the new quote button is pressed.
Use the Math.random function to generate a number between 0 and a total number of quotes fetched from the API. This number is the index of quotes stored in the array.
Each element stored in the array is an object which has the property text and author. Below is the image of the object:
Get the quote and the author from the array.
Set the author to anonymous if the author is undefined.
Initialize a boolean variable to get to know which side is currently displayed.
If the front side is displayed, change the quote on the backside and vice versa.
Step 3 (Fetching the quotes from the API):
The fetch API in JavaScript allows us to make HTTP requests to web servers.
Use the type.fit API to fetch the quotes.
Since fetching data from an API is an asynchronous process, we can use the async function or promises. Here we have used promises to fetch the data and store it in our array.
You can learn more about JavaScript promises here.
Step 4 (Adding functionality to the button):
Add an onclick function to the button.
Rotate the Quote Box, when the button is clicked using the rotateB and rotateF classes defined in the CSS stylesheet.
Initially rotate the backside of the box to 180 degrees.
RotateB rotates the backside of the box to 0 degrees i.e to its initial position.
RotateF rotates the front side of the box to 180 degrees i.e flips it behind.
Call the displayQuote function to display a new quote.
You can learn more about JavaScript buttons here.
Below is the entire JavaScript code generated by following the above steps:
Javascript
// Global Variable used to store the quotes // fetched from the APIvar data;let front = true;  // Getting the front and the back author boxesconst authors = document.querySelectorAll(".author");  // Getting the front and the back textsconst texts = document.querySelectorAll(".text");  // Getting the bodyconst body = document.getElementById("body");  // Getting the buttonsconst button = document.querySelectorAll(".new-quote");  const blockFront = document.querySelector(".block__front");const blockBack = document.querySelector(".block__back");  const authorFront = authors[0];const authorBack = authors[1];  const textFront = texts[0];const textBack = texts[1];  const buttonFront = button[0];const buttonBack = button[1];    // An arrow function used to get a quote randomlyconst displayQuote = () =>{      // Generates a random number between 0     // and the length of the dataset    let index = Math.floor(Math.random()*data.length);      // Stores the quote present at the randomly generated index    let quote = data[index].text;      // Stores the author of the respective quote    let author = data[index].author;      // Making the author anonymous if no author is present    if(!author){        author = "Anonymous"    }      // Replacing the current quote and the author with a new one      if(front){        // Changing the front if back-side is displayed        textFront.innerHTML = quote;        authorFront.innerHTML = author;    }else{        // Changing the back if front-side is displayed        textBack.innerHTML = quote;        authorBack.innerHTML = author;    }          front = !front;  }  // Fetching the quotes from the type.fit API using promisesfetch("https://type.fit/api/quotes")    .then(function(response) {        return response.json();     }) // Getting the raw JSON data    .then(function(data) {          // Storing the quotes internally upon         // successful completion of request        this.data = data;           // Displaying the quote When the Webpage loads        displayQuote() });    // Adding an onclick listener for the buttonfunction newQuote(){          // Rotating the Quote Box    blockBack.classList.toggle('rotateB');    blockFront.classList.toggle('rotateF');      // Displaying a new quote when the webpage loads    displayQuote();}
Output: That’s it we are done with our application. If you have followed along the end result should look something like this :
Picked
Technical Scripter 2020
JavaScript
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
JavaScript | Promises
How to filter object array based on attributes?
Lodash _.debounce() Method
JavaScript String includes() Method
How to map, reduce and filter a Set element using JavaScript ?
JavaScript | fetch() Method