Build a Random Quote Generator using JavaScript
Learn JavaScript by building a random quote generator - designed for beginners.

I am a Front end developer currently working on React JS, HTML, CSS, Python, Vue JS, Webpack, Babel, AEM etc.
Search for a command to run...
Learn JavaScript by building a random quote generator - designed for beginners.

I am a Front end developer currently working on React JS, HTML, CSS, Python, Vue JS, Webpack, Babel, AEM etc.
This article of yours Kartika is really worth reading it covered most of the necessary steps to generate random numbers. I would also recommend you to go through this amazing piece of Content .
Great! If you want more codes try this api quote library by freecodecamp over github. I also used it while making the random quote generator. Plus, you'll get know how apis work. 😉
Here is one with Chuck Norris API - https://blog.kritikapattalam.com/random-quotes-from-chuck-norris-api
You have explained the background story very nicely and also each of the steps. Nice article.
Thank you for the feedback. :)
This series talks about Tips & Tricks and simple projects you can build using JavaScript. Click on the articles below to read more.
Simple digital clock using JavaScript
Are you planning to start your coding journey?. Then this is for you - a roadmap to help you achieve your goals.

7 ways in which you can add files to your commit using git add

As a website user, one would have come across links or buttons which say "Click to download" or "Download" on a website. Have you ever wondered how can you add one to your website?. Keep reading!!!. As part of this blog let us see how one can crea...

Display Hello World and custom message using two-way data binding

Build a random quote generator using an API - JavaScript

Kritika Pattalam Bharathkumar | Web Developer - The official blog of Kritika Pattalam Bharathkumar
22 posts
Front End Engineer | Writes about HTML, CSS, JavaScript and everything related to web development | Follow me on Twitter let's chat.
The best way to learn to code is by practice and by building small projects. As part of this blog, let's build a beginner-friendly random quote generator in JavaScript.
Check out my previous blog post Build a Simple Clock using JavaScript.
Let's get started!!!.
Create the list of files as listed below
HTML is going to be very simple, nothing fancy here. In the below HTML,
A main outer container div which is going to hold the below elements
- a paragraph tag to display the quote
- a paragraph tag to display the author
- a button - onclick of which we will generate random quotes
<!Doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Random Quote Generator</title>
<link rel="stylesheet" href="styles.css">
<script src="script.js"></script>
</head>
<body>
<div class="outer-container">
<p id="quotes"></p>
<p id="author"></p>
<button id="generate">Generate</button>
</div>
</body>
</html>
Let's break this down into four steps
This can be done in two ways using function expression or vs function declaration. Read more about it here . The main difference with function expression is they are not hoisted, you cannot call the function expression before they are declared.
Now save this file, and open index.html in your browser. In the chrome developer tool console, you should see the text "hi". What happens here is, once the entire window including the DOM & assets is loaded, generateQuote function is called.
As per MDN docs, The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links, and sub-frames have finished loading.
const generateQuote = function() {
const quotes = [
{
quote: "Do not pity the dead, Harry. Pity the living, and, above all those who live without love.",
author: "Albus Dumbledore"
},
{
quote: "It is impossible to manufacture or imitate love",
author: "Horace Slughorn"
},
{
quote: "Being different isn't a bad thing. I mean that you are brave enough to be yourself.",
author: "Luna Lovegood"
},
{
quote: "If you want to know what a man’s like, take a good look at how he treats his inferiors, not his equals.",
author: "Sirius Black"
},
{
quote: "Never trust anything that can think for itself if you can’t see where it keeps its brain.",
author: "Arthur Weasley"
},
{
quote: "Every human life is worth the same, and worth saving.",
author: "Kingsley Shacklebolt"
},
{
quote: "Have a biscuit, Potter.",
author: "Minerva McGonagall"
},
{
quote: "Happiness can be found even in the darkest of times if one only remembers to turn on the light.",
author: "Albus Dumbledore"
},
{
quote: "Socks are Dobby’s favorite, favorite clothes, sir!",
author: "Dobby"
}
];
console.log("Hi");
}
window.onload = function() {
generateQuote();
}
First, let's see how to get the array values. Array values can be retrieved by their indexes. The index of an array starts from 0 to arraylength - 1. This means array index 0 will have the below values
{
quote: "Do not pity the dead, Harry. Pity the living, and, above all those who live without love.",
author: "Albus Dumbledore"
}
So if you want to print the fourth value, our index would be 3 [Remeber the index starts from 0 ] , so let's try to access the values for quotes and author using the index
//Syntax : arrayVariableName[index]
console.log(quotes[3].quote); // If you want to know what a man’s like, take a good look at how he treats his inferiors, not his equals.
console.log(quotes[3].author); // Sirius Black
The next thing we want to do is pick a random quote from the array. In the previous step we saw that we can access the quote using the index number, so we are going to need a random number to pick the quote.
As per MDN Docs, Math.random() returns a floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive).
Since math.random returns a floating-point number eg: 0.65 and in order to access the array values we need an integer so let's use math.floor which will give us an integer
As per MDN Docs, Math.floor() returns a number representing the largest integer less than or equal to the specified number.
in order to return a more efficient number let's multiply the random number with the array length and use math.floor which will return us an integer and save that value in a variable.
let arrayIndex = Math.floor(Math.random() * quotes.length);
document.getElementById("quotes").innerHTML = quotes[arrayIndex].quote;
document.getElementById("author").innerHTML = quotes[arrayIndex].author;
Now try saving the file, and when you open the index.html in the browser you should see a quote and author being displayed. When you refresh the browser, you should see a different quote
In the previous step, we were able to see different quotes being displayed every time when we refresh the browser because for every refresh the function gets called, which returns a random index number, displaying a random quote.
So now let's attach a eventlistener onclick to the button, which when clicked will call the generateQuote function
As per MDN docs, The EventTarget method addEventListener() sets up a function that will be called whenever the specified event is delivered to the target.
//Final JavaScript
const generateQuote = function() {
const quotes = [
{
quote: "Do not pity the dead, Harry. Pity the living, and, above all those who live without love.",
author: "Albus Dumbledore"
},
{
quote: "It is impossible to manufacture or imitate love",
author: "Horace Slughorn"
},
{
quote: "Being different isn't a bad thing. I means that you are brave enough to be yourself.",
author: "Luna Lovegood"
},
{
quote: "If you want to know what a man’s like, take a good look at how he treats his inferiors, not his equals.",
author: "Sirius Black"
},
{
quote: "Never trust anything that can think for itself if you can’t see where it keeps its brain.",
author: "Arthur Weasley"
},
{
quote: "Every human life is worth the same, and worth saving.",
author: "Kingsley Shacklebolt"
},
{
quote: "Have a biscuit, Potter.",
author: "Minerva McGonagall"
},
{
quote: "Happiness can be found even in the darkest of times, if one only remembers to turn on the light.",
author: "Albus Dumbledore"
},
{
quote: "Socks are Dobby’s favorite, favorite clothes, sir!",
author: "Dobby"
}
];
let arrayIndex = Math.floor(Math.random() * quotes.length);
document.getElementById("quotes").innerHTML = quotes[arrayIndex].quote;
document.getElementById("author").innerHTML = quotes[arrayIndex].author;
}
window.onload = function() {
generateQuote();
document.getElementById("generate").addEventListener('click', generateQuote);
}
Now you should have a working random quote generator, which generates random quotes onclick of a button. Now go ahead and try to load different quotes every few minutes or an hour. [Tip: Call the function inside setInterval, instead of onclick]
Follow me on Twitter | LinkedIn for more web development related tips and posts. Feedbacks and suggestions are welcome.
Checkout my other blog post series