The Wayback Machine - https://web.archive.org/web/20240905170123/https://www.geeksforgeeks.org/random-quote-generator-using-html-css-and-javascript/
Open In App

Random Quote Generator Using HTML, CSS and JavaScript

Last Updated : 26 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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: rotateY(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 API
var data;
let front = true;

// Getting the front and the back author boxes
const authors = document.querySelectorAll(".author");

// Getting the front and the back texts
const texts = document.querySelectorAll(".text");

// Getting the body
const body = document.getElementById("body");

// Getting the buttons
const 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 randomly
const 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 promises
fetch("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 button
function 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 :



Similar Reads

Design a Random Quote Generator in Tailwind CSS
This project demonstrates the creation of a simple Random Quote Generator web application using HTML, Tailwind CSS for styling, and JavaScript for functionality. The application generates random quotes and their authors upon clicking the "Generate Quote" button, offering an interactive and visually appealing experience. Prerequisites / Technologies
3 min read
Build Random Quote Generator using VueJS
We are going to build a Random Quote Generator using Vue.js. This application will fetch random quotes from an API and display them on the screen. Users will have the option to copy the quote to their clipboard or generate a new random quote. Prerequisites:Node.jsVue.jsApproachWe'll create a Vue.js component called QuoteGenerator that fetches rando
4 min read
Create a Random Quote Generator using React-Native
React Native is the most flexible and powerful mobile application development framework, which has various features embedded into it. Using this framework, we can create different interactive applications. Creating a Random Quote Generator using React Native is one of the interactive project which utilizes the API to generate the random quote and p
4 min read
Random Quote Generator App using ReactJS
In this article, we will create an application that uses an API to generate random quotes. The user will be given a button which on click will fetch a random quote from the API and display it on the screen. Users can generate many advices by clicking the button again. The button and the quotes are displayed beautifully using CSS styling to create a
3 min read
Create a Quote Generator Web App with Pure JavaScript using an API
In this tutorial we are going to create a web app that fetches motivational and inspirational quotes using an API. Application Requirements: Bootstrap 4 CDNAPI : https://type.fit/api/quotesJavaScriptHTMLSteps: Follow the below steps to create a quote generator. Step 1 Fetch: We are using inbuilt fetch Function of JavaScript for fetching the data fr
3 min read
Quote Generator App using NextJS
In this article, we will build an quote generator using NextJS. The user will be given a button that, when clicked, will retrieve a random quote from the API and display it on the screen. By clicking the button again, users can generate a large number of advices. Technologies Used/PrerequisitesIntroduction to NextNext ComponentReact HooksNPM or NPX
3 min read
Quote Generator App Using Angular
A Quote Generator App is a simple application that displays random quotes to users. It is a great project for practising Angular basics such as components, services, data and API integration. Here we develop a simple Quote Generator App using Angular. This application can able to display a new Quote when you click on the Quote Generator button. In
6 min read
Design Random Color Generator using HTML CSS and JavaScript
The Random Color Generator application can Generate new and random colors each time the user clicks on the Generate Color button. The user has the feature to Copy the HEX and RGB code of the generated color for the application. There is Dark Mode functionality, through which the user can view the generated color in the Dark Mode also and can toggle
4 min read
Inspirational Quote Generator with React
The Inspirational Quotes Website is a web app constructed using React. It showcases quotes to inspire and uplift users. Users have the ability to explore a selection of quotes and even share their quotes on social media. There is an option for navigating back to the already read quotes and a share button for social profiles. The background theme ch
3 min read
Random Image Generator using JavaScript
In this article, we will learn how to generate random images in fixed intervals using only HTML, CSS, and JavaScript. Approach: The pictures which are going to be generated randomly on the website should be stored in the form of an array, these pictures are then displayed to the user within a regular time interval. We use the setInterval() function
4 min read
Random String Generator using JavaScript
JavaScript is a lightweight, cross-platform, interpreted scripting language. It is well-known for the development of web pages, many non-browser environments also use it. JavaScript can be used for Client-side developments as well as Server-side developments. In this article, we need to create a Random String Generator using Javascript that will ge
7 min read
Build a Random Number Generator in Tailwind CSS
A Random Number Generator (RNG) is a tool that generates a random number within a specified range. By combining Tailwind CSS's utility classes with JavaScript, you can create a simple and visually appealing RNG that can be easily integrated into any web application. Approach:Create an HTML file and include the necessary Tailwind CSS CDN link in the
2 min read
Number Sequences Generator using HTML CSS and JavaScript
In this article, we are going to implement a number sequence generator based on HTML, CSS, and JavaScript. In this program, we have three different types of sequences: the Fibonacci Series, the Prime Number Series, and the Even Odd Number Series. Preview of final output: Let us have a look at how the final output will look like. PrerequisitesHTMLCS
5 min read
YouTube Video Embed Code Generator Tool using HTML CSS and JavaScript
In this article, we will see How to create your own YouTube Video embed code generator tool using the basics of HTML, CSS, and JavaScript. With this tool, we can create responsive embed code for responsive video output on all devices. We can make use of this tool and add the generated code in Blogger, WordPress, Wix, Google Sites, custom websites,
4 min read
How to create a Color Generator using HTML CSS and JavaScript ?
In this article, we will develop a Color Generator application using HTML, CSS, and JavaScript. In this application, we have created the Multi Format color generator. Users can select Colour Types like RGB, HEX, and CMYK. Use the sliders to customize the color and Inout field in case of HEX and color picker to directly change the color with color i
6 min read
How to create RGB color generator using HTML CSS and JavaScript ?
In this article, we will create a RGB color generator using HTML, CSS, and JavaScript. Using RGB color generator, we can construct all the colors from the combination of Red, Green, Blue colors. Each color is represented by the range of decimal numbers from 0 to 255 (256 levels for each color). So, the total number of available colors is 256 x 256
3 min read
How to create Hex color generator using HTML CSS and JavaScript?
Hex color codes are six-digit combinations representing the amount of red, green, and blue (RGB) in a color. These codes are essential in web design and development for specifying colors in HTML and CSS. The hex color generator provides the hex code for any selected color, making it a valuable tool for designers and developers. Approach to Generati
2 min read
How to create linear-gradient color generator using HTML, CSS and JavaScript ?
Creating a background generator using HTML, CSS, and JavaScript is an excellent way to add interactive and visually appealing features to your web projects. This tool allows users to generate gradient backgrounds based on their selected color values. In this article, we'll walk you through the steps to build a background generator, including settin
2 min read
Captcha Generator using HTML CSS and JavaScript
A captcha is a way of identifying a user whether the user is human or not. A captcha is made up with the help of combining letters and digits. it ensures that the user who is trying to access the platform is a human. So without wasting the time let's get started. Application of CaptchaForm Authentication: For login and sign up it can be used to ens
3 min read
Create an QR Code Generator Project using HTML CSS & JavaScript
In today's digital world, QR codes are widely used and provide a practical way to share information and access content with a quick scan. This deeply manually operated will show you step-by-step how to create a QR code generator from scratch using HTML, CSS, and JavaScript. This article will give you the knowledge necessary to develop an intuitive
3 min read
Navigating the Labyrinth: A Maze Generator Game Using HTML CSS & JavaScript
This article will help you make a simple yet interesting maze game, combining the power of HTML, CSS, and JavaScript to immerse the players. Let's explore the development of a maze generator game, where players can navigate through a new labyrinth with each refresh, thanks to the implementation of a Backtracking Algorithm. Preview Image: Approach:T
11 min read
Create a Emoji Generator Using HTML CSS & JavaScript
While communicating with our friends, we always use the emoji to represent our feelings and emojis. There are many emojis that represent our emotions and feelings. As developers, we can generate a random emoji on every click of the button, and we can also copy that emoji and paste it into our chat box or in the messaging area. This project has HTML
7 min read
HTML | DOM Quote Object
The Quote Object in HTML DOM is used to represent the HTML &lt;q&gt; element. The quote element can be accessed by using getElementById() method.Property Value: It contains single attribute value cite. This attribute is used to set or return the value of the cite attribute in a &lt;q&gt; element.Syntax: document.getElementById("ID"); Where ID is as
2 min read
HTML | DOM Quote cite Property
The HTML DOM Quote cite Property is used to set or return the cite attribute of a quotation. The cite attribute specifies the source URL of a quotation. Syntax: It returns the cite property. quoteObject.cite It is used to set the cite property quoteObject.cite = URL Property Values: It contains single value URL which is used to specify the URL of t
2 min read
Build a Random Name Generator using ReactJS
In this article, a Random Name Ge­nerator will be created using React.js. Building a Random Name Generator means creating a program or application that generates random names, typically for various purposes like usernames, fictional characters, or data testing. It usually involves combining or selecting names from predefined lists or patterns. Prer
4 min read
Build a Random User Generator App Using ReactJS
In this article, we will create a random user generator application using API and React JS. A Random User Generator App Using React Js is a web application built with the React.js library that generates random user profiles. It typically retrieves and displays details like names, photos, and contact information to simulate user data for testing and
4 min read
Create a Random User Generator using jQuery
With the use of the API and jQuery, we'll create a random user generator app. A straightforward web application called "jQuery Random User Generator" makes use of jQuery and the RandomUser.me API to generate random user data and present it in a visually appealing way. Users of this project can click a button to get random user information, such as
3 min read
Build a Password Generator App with HTML CSS and JavaScript
In this article, we will build a password generator application using HTML, CSS, and JavaScript. This application will generate strong and secure passwords based on user preferences, such as password length and character types. It aims to provide a convenient tool for users to generate random passwords that are difficult to guess and enhance their
3 min read
Build An AI Image Generator Website in HTML CSS and JavaScript
In this article, we are going to build an AI image generator website using HTML, CSS, and JavaScript. We incorporated API integration to fetch data, providing users with an effortless and dynamic experience in generating AI-driven images. An AI image generator website should have an input bar at the top of it, which simply accepts the text entered
3 min read
How to specify the source URL of the quote using HTML5 ?
In this article, we will learn how to specify the source URL of the quotation mark using HTML. We perform this task just by using a cite attribute of the &lt;q&gt; element in the document. This property contains the string value which represents the URL of the quotation mark. Syntax: &lt;q cite="URL"&gt; Example: Below code illustrates the use of t
1 min read