How to Build a Random Quote Generator with JavaScript and HTML using an API?

How to Build a Random Quote Generator with JavaScript and HTML using an API?

In this tutorial, I will walk you through building a simple random quote generator using an API. This tutorial will help you understand how you can integrate an API into your web applications. If you have prior knowledge of HTML, CSS, and JavaScript, following this tutorial will be easier for you. If you are an absolute beginner, don’t worry I will try my best to explain each part in detail.

By the end of this tutorial, you will build a fully functional random quote generator like this one that will have the following features:

  • Generates a random quote every time a user clicks on New Quote button
  • Background color changes with each random quote
  • Tweet Me button to share the quote on Twitter

To get started building this project, we need the following three things:

  • A Text Editor
  • A Web Browser
  • An API

For this tutorial, I will be using Mozilla Firefox browser (any browser will work fine), Visual Studio Code (or you can choose your favorite text editor) and Forismatic API.

Let’s get started!

Before we start any project, we have to create a folder that will contain all our files. Create an empty folder anywhere you like and rename it to “random-quote-generator“. Open this folder in Visual Studio Code by simpling dragging this folder inside VS Code (in other text editors also it opens the folder). Now, right-click inside VS Code inside a folder and select “New Folder” to create two folders named “css” and “js“. Inside these folders right click and select “New File” to create “styles.css” and “scripts.js” file respectively. Now finally create “index.html” file in the main project folder. By now, your folder structure should look like this one:

How to Build a Random Quote Generator with JavaScript and HTML using an API? 1

Our random quote generator project contains three parts: HTML, CSS, and JavaScript. With HTML, we will code the layout and style it with CSS. With the help of JavaScript, we will integrate an API and manipulate our DOM. Each section has been discussed below in detail.

Contents

Random Quote Generator – HTML Part

Index.html is the file that the browser will read and display. So, open your index.html file and type the following code inside or just type “html:5” in VS Code and press tab button to automatically insert the code and add some following lines of codes to set up the index file:

<!DOCTYPE html>
<html lang="en">
<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="Nabin Jaiswal">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <!-- END OF META INFORMATION -->    

    <title>Random Quote Generator</title>

    <!-- BOOTSTRAP CDN-->
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">

    <!-- FONTAWESOME CDN -->
    <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

    <!-- GOOGLE FONT -->
    <link href="https://fonts.googleapis.com/css?family=Acme" rel="stylesheet"> 

    <!-- CUSTOM STYLESHEET -->
    <link rel="stylesheet" href="css/styles.css">
</head>
<body>

    
    <!-- JQUERY CDN -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <!-- BOOTSTRAP JAVASCRIPT -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>

    <!-- CUSTOM JAVASCRIPT -->
    <script src="js/scripts.js"></script>
</body>
</html>

I know it’s a bit more confusing for you. But let me explain you each line code in detail.

<!DOCTYPE html> : It is an instruction to the web browser about what version of HTML the page is written in.

<head> tag: The HTML <head> tag is used for indicating the head section of the HTML document. Tags included inside head tags are not displayed in a browser window.

<meta> tag: The <meta> tag provides metadata about the HTML document.

<title> tag: With this tag, we specify the title to be displayed in web browser.

<link> tag: It is used to link style sheets and fonts. Here, we have linked Bootstrap stylesheet, FontAwesome Icon Fonts, Google Font (Acme) and our custom “styles.css“.

<body> tag: The tags inside body tags will be displayed in the browser.

<script> tag: WIth the help of this tag, we link the required JavaScript file. Here, we have linked jQuery, Bootstrap JavaScipt, and our own “scripts.js” file.

Now, it’s time we add some tags inside <body> to display in the browser. I have used Bootstrap framework for responsive layout. Inside body tag, we will be creating one <h1> tag to specify the title, a <div> to display the quote, two <a> tags for “New Quote” and “Tweet Me” and additional div to include developer detail (you can include your own or omit this one).

Just below the <body> tag, write this code or just copy paste it:

<div class="container">
        <div class="row">
            <div class="col-md-12 title">
                <h1>Random Quote Generator</h1>
            </div>
            <div class="col-md-12 quoteArea">
                <p id="randomQuote"></p>
            </div>

            <div class="col-md-12 buttons">
                <a href="#">Tweet Me</a>

                <a href="#">New Quote</a>
            </div>

            <div class="col-md-12 creator">Made with love by
                <a href="https://codepen.io/nabinjaiswal/" target="_blank">nabinjaiswal</a>
            </div>
        </div>
</div>

Now your text editor should look like this one:

How to Build a Random Quote Generator with JavaScript and HTML using an API? 2

Here, we have defined classes title, quoteArea, buttons, and creator to style our h1 tag, quote, buttons and author respectively. We have also defined an empty <p> tag with id randomQuote where we will insert the random quote via JavaScript. We will cover this in JavaScript part. We have used a few Bootstrap classes like container, row and grid classes. If you open your index.html file in a browser, it should look like this:

Before we dive into CSS section and style our HTML document, let us add FontAwesome icons and some Bootstrap classes to our <a> tag to make it look like a button. After adding some bootstrap classes your code should look like this:

<div class="col-md-12 buttons">
       <a href="#" class="btn btn-info" target="_blank" id="tweetMe" role="button"> <i class="fa fa-twitter"></i>   Tweet Me</a>

       <a href="#" class="btn btn-info" id="newQuote" role="button"> <i class="fa fa-quote-left"></i>  New Quote</a>
</div>

Finally, combining all the above codes, the index.html should contain the following code:

<!DOCTYPE html>
<html lang="en">

<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="Nabin Jaiswal">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <!-- END OF META INFORMATION -->

    <title>Random Quote Generator</title>

    <!-- BOOTSTRAP CDN-->
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4"
        crossorigin="anonymous">

    <!-- FONTAWESOME CDN -->
    <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN"
        crossorigin="anonymous">

    <!-- GOOGLE FONT -->
    <link href="https://fonts.googleapis.com/css?family=Acme" rel="stylesheet">

    <!-- CUSTOM STYLESHEET -->
    <link rel="stylesheet" href="css/styles.css">
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-md-12 title">
                <h1>Random Quote Generator</h1>
            </div>
            <div class="col-md-12 quoteArea">
                <p id="randomQuote"></p>
            </div>

            <div class="col-md-12 buttons text-center">
                <a href="#" class="btn btn-info" target="_blank" id="tweetMe" role="button">
                    <i class="fa fa-twitter"></i>   Tweet Me</a>

                <a href="#" class="btn btn-info" id="newQuote" role="button">
                    <i class="fa fa-quote-left"></i>  New Quote</a>
            </div>

            <div class="col-md-12 creator">Made with <i class="fa fa-heart"> </i>  by
                <a href="https://codepen.io/nabinjaiswal/" target="_blank">nabinjaiswal</a>
            </div>
        </div>
    </div>


    <!-- JQUERY CDN -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <!-- BOOTSTRAP JAVASCRIPT -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm"
        crossorigin="anonymous"></script>

    <!-- CUSTOM JAVASCRIPT -->
    <script src="js/scripts.js"></script>
</body>

</html>

Now, if you view an index.html file in a browser, you will see similar to this one:

How to Build a Random Quote Generator with JavaScript and HTML using an API? 3

Congratulations! you have successfully come this far. Now lets dive in CSS section make it look awesome.

Random Quote Generator – CSS Part

Since we have used Bootstrap, it has already provided some basic styling to our elements. We will just refine it or define in some cases. Copy and paste the following code into “styles.css” file:

body{
  font-family: 'Acme', sans-serif;
  background:#34495e;
  color:#fff;
}
.title{
  padding-top:40px;
  text-align: center;
  margin-bottom: 50px;
}
.quoteArea{
  padding:40px;
  font-size: 30px;
  border:5px solid #fff;
  margin-bottom: 30px;
  color: #fff;
}
.fa-heart{
    color:#ff1237;
}
.creator, .creator a{
    text-align: center;
    padding-top: 20px; 
}

After adding these styling, when you view the index file it should look like this:

How to Build a Random Quote Generator with JavaScript and HTML using an API? 4

You can see yourself, how much difference these few lines of code made to our random quote generator. CSS part is done, let us finish our final part.

Random Quote Generator – JavaScript Part

This is main and last part of our random quote generator app. In this section, we will be integrating Forimatic API and manipulate our HTML elements. So before we dive into creating actual coding, lets first know what does  API means. An Application Programming Interface (API) is a particular set of rules (‘code’) and specifications that software programs can follow to communicate with each other. It serves as an interface between different software programs and facilitates their interaction, similar to the way the user interface facilitates interaction between humans and computers.

In JavaScript file “scripts.js“, we will define two functions randomQuote() and randomColor() to get a random quote to display and change background color everytime a user clicks New Quote respectively.

In randomQuote() function, we will make a request to API, which will return us data in JSON format. The randomQuote() should look like this:

function randomQuote() {
    $.ajax({
        url: "https://api.forismatic.com/api/1.0/?",
        dataType: "jsonp",
        data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
        success: function (quoteData) {

            
        }
    });
}

Let me walk you briefly through the code above:

We make an ajax request to get the data. The url specifies the API address, dataType specifies the data type we are getting, data specifies the method, format, and language. We store the result in quoteData. The quoteData contains quoteText and quoteAuthor that we need.

In some result, the quoteAuthor data may be missing. In that case, if quoteAuthor is blank or missing, we simply replace it with Unknown.

if (quoteData.quoteAuthor === '') {
     quoteData.quoteAuthor = 'Unknown';
};

Did you remember the empty div with id randomQuote. Now, we need to grab it and insert quoteText value inside it. The following code does this:

$("#randomQuote").html("<p id='randomQuote'><i class=\"fa fa-quote-left\"></i>    " 
+ quoteData.quoteText + "<br/> <div class=\"text-right\"> ‐" + quoteData.quoteAuthor + "</div></p>");

Now we will also add some attribute to Tweet Me button with the following code:

$("#tweetMe").attr("href", "https://twitter.com/home/?status=" + quoteData.quoteText + ' - ' + quoteData.quoteAuthor);

The final code for randomQuote() function should look like this:

function randomQuote() {
    $.ajax({
        url: "https://api.forismatic.com/api/1.0/?",
        dataType: "jsonp",
        data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
        success: function (quoteData) {

            if (quoteData.quoteAuthor === '') {
                quoteData.quoteAuthor = 'Unknown';
            };

            $("#randomQuote").html("<p id='randomQuote'><i class=\"fa fa-quote-left\"></i>    " + quoteData.quoteText + "<br/> <div class=\"text-right\"> ‐" + quoteData.quoteAuthor + "</div></p>");
            $("#tweetMe").attr("href", "https://twitter.com/home/?status=" + quoteData.quoteText + ' - ' + quoteData.quoteAuthor);
        }
    });
}

Now, its define the randomColor() function. In this function, we define an array called colors (you can define your own set of colors) and store color codes. Then we define a variable choosedColor to chose a random color from colors array. The randomColor() should look like this:

function randomColor(){
  var colors = ['#34495e','#6C7A89','#ABB7B7', '#336E7B', '#8E44AD', '#674172', '#D2527F','#96281B','#34495e','#16a085','#f39c12','#d35400','#c0392b','#7f8c8d','#8e44ad'];
  var choosedColor = colors[(Math.floor(Math.random()*16))];
  return choosedColor;
};

If you view the index file, you will see nothing.It is because we have not called this functions yet. Include the given code below to call these functions:

$(function() {
  randomQuote();
  randomColor();
});

Now if you view the index file, you will see any random quote. Tweet Me button is working fine but New Quote is not working. Whenever the user clicks on the New Quote button, it should change the background and also call the randomQuote() function. We can achieve this with the following code:

$("#newQuote").click(function(){
  $('body').css({
    'background':randomColor(),
    'transition':'all linear 0.2s'
  });
  randomQuote();
 });

The random quote generator should work properly. Your “scripts.js” should contain the following code:

function randomQuote() {
    $.ajax({
        url: "https://api.forismatic.com/api/1.0/?",
        dataType: "jsonp",
        data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
        success: function (quoteData) {

            if (quoteData.quoteAuthor === '') {
                quoteData.quoteAuthor = 'Unknown';
            };

            $("#randomQuote").html("<p id='randomQuote'><i class=\"fa fa-quote-left\"></i>    " + quoteData.quoteText + "<br/> <div class=\"text-right\"> ‐" + quoteData.quoteAuthor + "</div></p>");
            $("#tweetMe").attr("href", "https://twitter.com/home/?status=" + quoteData.quoteText + ' - ' + quoteData.quoteAuthor);
        }
    });
}

function randomColor() {
    var colors = [
        '#34495e',
        '#6C7A89',
        '#ABB7B7',
        '#336E7B',
        '#8E44AD',
        '#674172',
        '#D2527F',
        '#96281B',
        '#34495e',
        '#16a085',
        '#f39c12',
        '#d35400',
        '#c0392b',
        '#7f8c8d',
        '#8e44ad'
    ];
    var choosedColor = colors[(Math.floor(Math.random() * 16))];
    return choosedColor;
}

$(function () {
    randomQuote();
    randomColor();
});

$("#newQuote").click(function () {
    $('body').css({'background': randomColor(), 'transition': 'all linear 0.2s'});
    randomQuote();
});

If you made this far, congratulations you have successfully made a random quote generator.

How to Build a Random Quote Generator with JavaScript and HTML using an API? 5

Here’s a Github link to this project.

Wrapping Up

Instead of using an API, you can also create an array with a collection of quotes and choose random quote whenever the user presses the New Quote button. By using API, we avoided this step of adding quotes ourselves. I have hosted the project on Github. You are free to download and modify the code and even add some more functionalities like share on different social media.

Did you enjoy making this project? I did. Do let me know in the comment below if you faced any difficulties or have any doubts.

Leave a Reply

Your email address will not be published. Required fields are marked *