This Javascript Code Generates Random Quotes

cover
25 Apr 2024

What comes to your mind when you hear the word random quote using vanilla JavaScript? As far as I'm concerned, anything may be the case.

And there may be another scripting language that can make random quotes, but one of the most distinguished of them is using JavaScript to make a random quote.

You might have seen some social media apps that display people’s posts, but you must keep scrolling to see more posts. But according to what we will be building, you will have to click on a button to view a new quote.

Note: in this tutorial we will make use of an API, the API is used to fetch the quotes randomly across the web. By just clicking on the button the API fetches a new quotes. So without wasting much of your time, let's dive into this guide.

Prerequisite

  1. You need to have basic knowledge of HTML
  2. You need to have basic knowledge of CSS
  3. You need to have basic knowledge of JavaScript
  4. Also have a code editor(Sublime or VS code) etc.

Step-by-step JavaScript Random Quote Generator

A random quote pulls quotes randomly from an API or an array. In this article, we'll use JavaScript to produce quotes from an array as we design a random quote generator from scratch using HTML, CSS, and JavaScript only. Below is a step-by-step guide to going through to accomplish the random quote task.

Step 1: Is Making a New Project The project you’re about to build contains three pages: HTML, CSS, and JavaScript. so you’ll name the various pages will be named like this. index.html, style.css, script.js. After doing this you’re ready to move on to the next step.

Step 2: Constructing the framework This step will enable you to add a few HTML codes that will give your project structure.
Note: This section is probably the first thing to do after creating the folder and the files as stated above.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
    <!--META information-->
   <meta name="description" content="Random Quote Generator">
   <meta name="keywords" content="HTML,CSS,JavaScript, Quotes, API">
   <meta name="author" content="EmmyKolic">
   <!--End of META information-->
   <title>Random Quotes</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="button">
        <!--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>

Step 3: Adding Styles for the Classes In this section, we will be adding styles to the code using CSS, to build the quote generator. Note: This section is the next thing to do after creating the index.html file, you will create another file named style.css the style.css file will be linked to the HTML file.

Then you to style the layout of the HTML. Here’s the CSS code below.

* {
  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( 51, 255, 141 ),
    #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(27, 245, 235 , 0.5);
  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(170, 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;
}
.button {
  width: 100%;
  display: flex;
  padding: 10px;
  justify-content: space-between;
  align-items: center;
  margin: 9px;
}
.twitter {
  border: 1px solid rgb(102, 179, 255);
  border-radius: 4px;
  background-color: rgb(102, 179, 255);
  color: white;
  padding-bottom: 15px;
  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(22, 210, 248),
    #bcd7ffa8
  );
}
.container:hover {
  box-shadow: 0 10px 10px rgb(0, 180, 230);
}

Step 4: Incorporate a few lines of JavaScript code. In this step, we will incorporate some JavaScript code to build the quote generator. Note: This section is an essential part of this tutorial, Now you’ll create another file call it script.js.


Go through the code below you’ll see what was done clearly, We interacted with an API by using a link and saving inside a variable named url. To make this guide brief, go through the script.js you’ll notice a comment before each section. Here’s the JavaScript code below.

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();

Conclusion

We’ve come to the end of this tutorial, hopefully, you’ve gained a ton of value. On how to build random quotes project using vanilla JavaScript.

We’ve seen how to interact with an API, although that's not the only way or should I say best way to interact with an API. and how to tweet a quote from our JS code to your Twitter account.

Just discussing this tutorial has shown us a lot. So feel free to drop a comment! And if you want more tutorials, please follow me.

Till next time, Enjoy your day!

About The Author

Emmanuel Okolie is a full-stack laravel developer with 2+ years of experience in the software development industry. He has built full-fledged skills by fusing software development, writing, and teaching others what he does. His stacks are ReactJs, Laravel, PHP, JavaScript, and more.

He works as a freelancer, building websites for clients and writing technical manuals to instruct others on how to carry out his work.

Emmanuel Okolie would welcome the opportunity to speak with you. Kindly visit and follow him on Linked-In, Facebook, Github, Twitter, or his Website.