DEV Community

Codewithrandom Blogs
Codewithrandom Blogs

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 Generator from an API, upon the click of a button, and displays it in the browser.

Prerequisite
Basic knowledge of HTML
Basic knowledge of CSS
Basic knowledge of JavaScript

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 Code

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

As this Random Quote Generator mainly focuses on teaching JavaScript concepts, I assume that you must be familiar with the HTML syntax and easily understand above code but still we will discuss briefly about what’s happening in this html file.

In the code of Random Quote Generator body tag of our file we have three main section: 1. Heading 2. Form 3.Task Container and at last we are just linking our JavaScript file.

Heading section as you already guessed contains title of our app.

CSS Code

* {
  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(128, 255, 249),
    #acc9ffa8
  );
  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(0, 230, 130),
    #bcd7ffa8
  );
}
.container:hover {
  box-shadow: 0 10px 10px rgb(0, 180, 230);
}
Enter fullscreen mode Exit fullscreen mode

This is my styling for our Random Quote Generator app which you can easily understand by just reading once as I have also added comments specifying the role of the code. You can also come up with your own styling. And please send the link of your styling in comment section. I would love to see all of your creative styling.

JavaScript Code

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

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:-

Create a function getNewQuote().

Step 1:- 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.

Step 2:- 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.

Step 3:- 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.

Step 4:- 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.

Step 5:- 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.

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

You have just created a random quote generator. It will look something like this!

If you enjoyed reading this Random Quote Generator Using HTML, CSS, and JavaScript post and have found it useful for you, then please give a share with your friends, and follow me to get updates on my upcoming posts. You can connect with me on Instagram.

if you have any confusion Regarding Random Quote Generator Comment below or you can contact us by filling out our contact us form from the home section.

written by – Ninja_webTech

Top comments (0)