Random quotes generator

OpenJavaScript 0

Last updated: November 29, 2021.

In this tutorial, we cover how to create a random quotes generator.

The first feature of this project is the app will display a quote at random when first loaded. Second, the user can get another quote at random without refreshing the page by clicking a “Get another quote” button. This will be programmed so that the random quote displayed is never the same as the previous quote.

Quotes will be injected dynamically onto the page from storage in a JavaScript object, replicating the kind of data one would retrieve from an API call after parsing.

Step 1: HTML markup

Since the quotes themselves are not hardcoded in the HTML but injected dynamically from JavaScript the HTML markup for this project is minimal. In fact, because we will use a JavaScript template literal to create the HTML template into which the quotes will be injected, the only necessary HTML is an empty div element with an appropriate id:

<div id="randomQuotes"></div>

Step 2: JavaScript

2.1: Creating the quotes

Because the content is dynamically injected from JavaScript, it is necessary to have the quotes stored in JavaScript.

For this, let’s create an array of objects. Within each of these objects, the author and quote itself is stored in key: value format.

For the sake of this tutorial, we work with eight quotes but you can add as many as you like. These could even be retrieved first from a third-party quote generator API.

const quotes = [
    {author: "Oscar Wilde",
    quote: "Be yourself; everyone else is already taken."},
    {author: "Albert Einstein",
    quote: "Two things are infinite: the universe and human stupidity; and I'm not sure about the universe."},
    {author: "Mark Twain",
    quote: "If you tell the truth, you don't have to remember anything."},
    {author: "Caroline Rhea",
    quote: "My favorite machine at the gym is the vending machine."},
    {author: "Dale Carnegie",
    quote: "Remember, today is the tomorrow you worried about yesterday."},
    {author: "Bill Waterson",
    quote: "The surest sign that intelligent life exists elsewhere in the universe is that it has never tried to contact us."},
    {author: "Norm Crosby",
    quote: "When you go into court you are putting your fate into the hands of twelve people who weren’t smart enough to get out of jury duty."},
    {author: "Benny Hill",
    quote: "Have you noticed that all the people in favor of birth control are already born?"},
]

2.2: Generate a random number

Next, we want to generate a number at random that will allow us to select one of the quotes at random.

Below is a random number generator function, which we then call, inserting inside the min and max arguments values of 0 and quotes.length-1.

The min value is 0 because JavaScript starts counting from 0. And, to adjust for this, the max value is the length of the object array minus 1.

// Define random number generator function
function randomInteger(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// Call function and save result to variable
let randomNumber = randomInteger(0, quotes.length-1);

2.3: Templating selected quote

Next, we write a writeTemplate function that will generate the content.

In the function, we use backticks (`) to create a template literal inside which we create the HTML we would like for the app.

We use the interpolate syntax (${}) to add the quote content dynamically into the template. For this, we use the random number generated to the select a quote from the array of objects.

Notice that we include a button element at the end of the template literal and, after the template, add a ‘click’ event listener to it invoking the handleClick function. This function will select a different quote at random. We turn to the programming of this next.

function writeTemplate() {
    document.getElementById('randomQuotes').innerHTML = `
        <blockquote>
           <p>${quotes[randomNumber].quote}</p>
           <span><i>${quotes[randomNumber].author}</i></span>
        </blockquote>
        <button id="btn">Get another quote</button>
    `
    document.getElementById('btn').addEventListener('click', () => { handleClick() })
}

writeTemplate()

2.4: Getting another random quote

In the handleClick() function, we first clear the contents of our app by selecting the div element in our HTML and setting its innerHTML content to an empty string("").

Next, we call our random number generator again. This time we save it in a new variable called NewRandomNumber.

To make sure the same quote does not appear again, we check the value of NewRandomNumber against randomNumber. If it is the same, we invoke handleClick again, generating another random number. This process will continue until NewRandomNumber against randomNumber do not match. This is known as a recursive function.

If NewRandomNumber and randomNumber do not match, we proceed to overwrite the value of randomNumber with the value of NewRandomNumber.

Finally, the writeTemplate function is called, which will create the HTML template again, using the newly assigned value of randomNumber to select a quote.

function handleClick() {
    document.getElementById('randomQuotes').innerHTML = "";
    let NewRandomNumber = randomInteger(0, quotes.length-1);
    if (NewRandomNumber == randomNumber) { () => { handleClick } }
    else { randomNumber = NewRandomNumber}
    writeTemplate()
}

Step 3: Adding CSS

The focus of this tutorial has been the programming of the random quotes generator with JavaScript.

However, it is always nice to make a project look good! To get the same appearance for the app as in the project preview, add the following CSS:

/* Imports Open Sans font from Google Fonts*/
@import url('https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@1,300&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@300&display=swap');
body {
  font-family: 'Open Sans', sans-serif;
  /* Sets a linear color background */
  background-color: #FBAB7E;
  background-image: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%);
  background-repeat: no-repeat;
  height: 100vh;
}
h1 {
  text-align: center;
}
blockquote {
  /* Flex applied to center text vertically */
  display: flex;
  flex-direction: column;
  justify-content: center;
  font-size: 1.5rem;
  width:60%;
  /* Min-height so box size if fixed*/
  min-height: 31vh;
  max-height: auto;
  margin: 30px auto;
  font-style:italic;
  color: black;
  padding:1.2em 30px 1.2em 75px;
  border-left:8px solid #0039a3;
  border-radius: .25rem;
  box-shadow: rgba(0, 0, 0, 0.16) 0px 10px 36px 0px, rgba(0, 0, 0, 0.06) 0px 0px 0px 1px;
  line-height:1.6;
  position: relative;
  background: whitesmoke;
}

blockquote::before{
  font-family: Arial, Helvetica, sans-serif;
  content: "1C";
  color: 0039a3;
  font-size:4em;
  position: absolute;
  left: 10px;
  top:-10px;
  color: #0039a3;
}

blockquote span{
  display:block;
  color:#333333;
  font-style: normal;
  font-weight: bold;
  margin-top:1em;
}
button {
  font-family: Arial, Helvetica, sans-serif;
  display: block;
  margin: 1rem auto;
  color: #212529;
  text-align: center;
  border: 1px solid transparent;
  padding: .375rem .75rem;
  font-size: 1rem;
  line-height: 1.5;
  border-radius: .25rem;
  color: #fff;
  background-color: #007bff;
  box-shadow: rgba(0, 0, 0, 0.16) 0px 1px 4px, rgb(51, 51, 51) 0px 0px 0px 2px;
}

button:hover {
  background-color: #005fc4;
  cursor: pointer;
}

Summary

In this tutorial, we have covered how to create a random quotes generator using JavaScript by injecting content in dynamically from an array of objects (mimicing data from an API call after parsing).

Want to sharpen your HTML, CSS and JavaScript skills further? Visit our projects sections for more projects!