Cognitame

'A man is none the less a slave because he is allowed to choose a new master once in a term of years. Neither are a people any the less slaves because permitted periodically to choose new masters. What makes them slaves is the fact that they now are, and are always hereafter to be, in the hands of men whose power over them is, and always is to be, absolute and irresponsible.' -Lysander Spooner, No Treason

# 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: