Build a Random Quote Generator using JavaScript
Kritika Pattalam Bharathkumar
Posted on September 24, 2021
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.
What will we learn as part of this blog
- function declaration vs function expression
- window.onload function
- Math.random()
- Math.floor
- attaching onclick eventlistener to an element
Let's get started!!!.
Project structure
Create the list of files as listed below
- index.html
- script.js
- style.css [ styles if we have any. As part of this blog, I am not going to add any styles.].
HTML Structure - index.html
HTML is going to be very simple, nothing fancy here.
In the below HTML,
- link the stylesheet inside the head tag
- link the javascript file inside the head tag
- Inside the body tag we are going to have 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>
JavaScript
Let's break this down into four steps
- Create an array inside a function and call that function on window load.
- Retrieve the quotes/author from the array.
- Onclick of the button, pick a random quote(index) from the array to display.
- Use the index generated to display the quotes and author into the paragraph tag using innerHTML.
- Call the function onclick
1) Create an array inside a function and call that function on window load.
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.
- In the below example, I created a function called generateQuote, which contains an array called quotes and a console.log hi. I have declared quotes as a const variable because the value of the array is going to be always constant and will never change throughout this project.
- Next inside window.onload function I call the function generateQuote.
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();
}
2. Let's see how to retrieve the quotes/author from the array
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
3. Onclick of the button, pick a random quote(index) from the array to display.
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);
4. Use the index generated to display the quotes and author into the paragraph tag using innerHTML
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
5. Call the function onclick
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);
}
Output - Working Demo
Conclusion
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]
References
Follow me on Twitter | LinkedIn for more web development related tips and posts. Feedbacks and suggestions are welcome.
Posted on September 24, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 25, 2024