Presenting every visitor to your site with a random quote is a popular way to personalize a user’s experience. Often the quotes are stored in an external file, but if the corpus is relatively small - a dozen entries or less - it’s more efficient to store them directly the page, within their own script:
A Store of Wisdom
Each quote will always consist of two components - the quote and the cited author - making a JSON array the perfect method of storing the information:
const quotes = [
{
"quote" : "The only sin is ignorance",
"source" : "Christopher Marlowe"
},
{
"quote" : "A man is his own easiest dupe, for what he wishes to be true he generally believes to be true",
"source" : "Demosthenes"
},
{
"quote" : "A lie can travel halfway around the world while the truth is putting on its shoes",
"source" : "Mark Twain"
}
]
The markup on the page is created without content: if the JavaScript fails, the result won’t leave much to be tidied up. (Alternatively, we could fill the space between the tags with a default quote and citation).
<blockquote>
<p id="quotation"></p>
<footer>
<p id="source"></p>
</footer>
</blockquote>
A function draws a random quote from the JSON structure and places it as the innerText
of the quotation
paragraph using a template literal; a similar process is used for the cited source:
function randomQuote() {
let random = quotes[Math.floor(Math.random() * quotes.length)];
quotation.innerText = `“${random.quote}.”`;
source.innerText = random.source;
}
The function is called immediately on page load:
randomQuote();
Quotes on Demand
The CodePen demo associated with this article also has a button that can be used to pull new quotes:
<button id="genquote">Generate Quote</button>
Clicking the button also calls randomQuote
:
genquote.addEventListener("click", randomQuote)
Volubility
As the script stands, there’s no guarantee that a new random quote will not be the same as a previous quote; while more entries will reduce the occurrence of that, the probability will never diminish to 0. To achieve that, you could delete the key from the JSON object after it was chosen, or keep an array of the used random quotes and check that the new quote didn’t match any of those that had been previously displayed.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.
Check out the CodePen demo for this article at https://codepen.io/dudleystorey/pen/ORKWoE