'The Universe is full of dots. Connect the right ones and you can draw anything. The important question is not whether the dots you picked are really there, but why you chose to ignore all the others.' -Sam Thomsen

How to Display Random Text

by Ethan Glover, Tue, Jun 30, 2015

Displaying random text on a website is really simple. Basically, we’re going to write a function that, when called, generates a random number, uses that number to pick a quote from a list, and print out that quote inside some previously defined blockquote tags in the page HTML.

First, create a button that can be used to load the text and get new text if needed:

<button onclick="quote()">Load Quote</button>

This simple string is telling the browser to load the quote function on the click of the button.

Next, set aside some space for the quote appear. Later, we'll use the id specified to signal to the browser where to display the text.

<blockquote id="quoteHere"></blockquote>

Inside script tags, create a string array with all the possible options.

<script>
function quote() {
	var quotes = [ "Quote 1","Quote 2","Quote 3" ];
</script>

Next, use Math.random() to generate a random number, Math.floor to turn it into an integer, and quotes.length to determine the range of numbers generated. Together, it should look like this.

var dailyQ = quotes[Math.floor(Math.random() * quotes.length)];

Last, get the "quoteHere" id from the document that we created previously and output text using "innerHTML" as such.

document.getElementById("quoteHere").innerHTML = dailyQ;

Putting it all together, the code should look like this. (Just place it all within HTML tags on your webpage.)

<button onclick="quote()">Get New Quote</button>
<blockquote id="quoteHere"></blockquote>

<script>
function quote() {
	var quotes = [ "Quote 1","Quote 2","Quote 3" ];
	
	var dailyQ = quotes[Math.floor(Math.random() * quotes.length)];
	document.getElementById("quoteHere").innerHTML = dailyQ;
}
</script>

Demo: