Written by
Morgan
March, 12th, 2020

This post details a simple code example to help you create a random quote generator using Javascript. Something that you can easily integrate on your next project or expand upon depending on your requirements. I've attempted to break down the process into simple steps, but if you don't have the time to complete the example yourself you'll find a CodePen example at the bottom of the post.

Getting prepared

At the start I always think its a good idea to write down on paper what you are looking to achieve. Even if it is a relatively simple bit of code like this. It's just easier to know what you are aiming for and the steps to cet there should already be marked out before writing a single line of code. So lets have a quick think about what we would like this quote generator to do: - It needs an area to store the quotes. It needs to select one of those quotes at random and display that in HTML. It also needs to cycle through these quotes automatically.

Creating a Place to Store the Quotes

So the first step you need to get in place is an area to store the quotes. For this I have decided to use a basic array. In your JS file add the following code (You can add your choice of quotes here):

var quotes = [
  "The way to get started is to quit talking and begin doing",
  "If life were predictable it would cease to be life, and be without flavor",
  "Life is what happens when you're busy making other plans",
  "When you reach the end of your rope, tie a knot in it and hang on",
  "Never let the fear of striking out keep you from playing the game",
  "Life is either a daring adventure or nothing at all",
  "Love the life you live. Live the life you love",
  "If you really look closely, most overnight successes took a long time",
  "I failed my way to success",
  "Success is walking from failure to failure with no loss of enthusiasm",
];

Setting up the HTML Markup

Another nice and simple part here. We basically need a container for displaying the quote on the frontend. The class names used here are again up to you as these will only be used for styling the generator later on. In the example I've given the text area an ID of quoteArea. If you change this, make sure you update it in your Javascript file further down the line. In your HTML file add the following markup:

<div class="quotes">
  <article class="container">
    <h1 id="quoteArea"></h1>
  </article>
</div>

Start building up the function

Now that has been setup you need to create a querySelector that will reference the container that will hold each random quote. Add the following line to your JS file:

var quoteArea = document.querySelector("#quoteArea");

As you might already guess, this will find the tag with the ID quoteArea and store it in a variable of a similar name. Now you could get bogged down in modern Javascript here and use the new variable keywords, but for the moment that’s not a concern.

For the moment I’ll set things up in a function called changeQuotes which will do the bulk of the switching. In here it will do a few things - count the length of the quotes array, request a random number, and display a random quote. First up, you’ll need to find out the length of the array so within the changeQuotes function write the following:

function changeQuotes() {
  var quotesLength = quotes.length;
}

Next, you'll want to generate a random number. To do this we'll create another, separate function that will pick a random number between 0 and the length of the array. Add the following lines to your JS file:

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

function changeQuotes() {
  var quotesLength = quotes.length;
  var randomNum = getRandomInt(quotesLength);
}

Now, with the length of the array and the newly acquired random number, use that to create a variable called randomQuote and display the quote on the frontend using innerHTML

function changeQuotes() {
  var quotesLength = quotes.length;
  var randomNum = getRandomInt(quotesLength);
  var randomQuote = quotesLength[randomNum];

  quoteArea.innerHTML = randomQuote;
}

And to get the function running on the page load you can add the following to the javascript file:

changeQuotes();

Setting up a timer

But having one quote appear on page load probably is not what you are looking for, so a better solution will be to add a timer in that will update the quote after a number of seconds. First of all, add a variable to the top of the JS file that will hold the duration

var quoteArea = document.querySelector("#quoteArea");
var slideDuration = 10000; // 10 seconds

And within the changeQuotes function add the following line. This will create a timer that will repeat the changeQuotes function at the interval set in the slideDuration variable.

function changeQuotes() {
  var quotesLength = quotes.length;
  var randomNum = getRandomInt(quotesLength);
  var randomQuote = quotesLength[randomNum];

  quoteArea.innerHTML = randomQuote;

  setTimeout(changeQuotes, slideDuration);
}

And as you can see, the quote now changes every 10 seconds. Wonderful. But its a bit boring, so next up we'll add a few touches that will make the presentation a bit better. First up, place another setTimeout in the changeQuotes function. This one will control the removal of a fadeout class that will be used to style the quote transition and the changeover of the random quote. Add the following lines to your JS file:

function changeQuotes() {
  var quotesLength = quotes.length;
  var randomNum = getRandomInt(quotesLength);
  var randomQuote = quotesLength[randomNum];

  quoteArea.classList.add("fadeout");

  setTimeout(function () {
    quoteArea.innerHTML = randomQuote;
    quoteArea.classList.remove("fadeout");
  }, 1250);

  setTimeout(changeQuotes, slideDuration);
}

And add the following CSS to tart it up.

#quoteArea {
  opacity: 1;
  transition: opacity 0.75s, transform 0.75s;

  &.fadeout {
    opacity: 0;
    transform: translateY(1.25rem);
  }
}

.quotes {
  padding: 4rem 1rem;
}

.container {
  display: flex;
  justify-content: center;
  margin-left: auto;
  margin-right: auto;
  width: 90%;
  max-width: 600px;
  height: 100%;
  text-align: center;
  font-family: sans-serif;

  h1 {
    font: {
      family: "Pinyon Script", cursive;
      size: 3rem;
      weight: 300;
    }
    color: #2e2e2e;
    text-shadow: 0px 0px 8px rgba(50, 50, 50, 0.25);
  }
}

And thats it, you should now have a random quote generator that you can implement on your next project. Or, you can take what we have here and expand on it.

https://codepen.io/morgancarbonfourteen/pen/zYvWBxx

Return to journal