How to Generate Random Quotes in JavaScript

The Promenade theme that I’ve been writing about in my last few posts comes with the default text “PROMENADE WORDPRESS THEME BY AUDIOTHEME” in its footer. Most site owners customise this; for example Marianne Faithfull has set her text to “CONTACT | ACKNOWLEDGEMENTS | THEME BY AUDIOTHEME”. The teacher who I was using Promenade for wanted custom text too, but of a special kind, namely quotations about her subject that changed every few seconds. In this post and the next, I’ll explain how I did that for her.

All web browsers can run programs in a language called JavaScript. This can do a lot of things, such as checking data typed into forms and then submitting it automatically. What’s of interest today is that JavaScript can also “edit” the page in your browser, doing things such as inserting new pieces of HTML, hiding and then revealing existing pieces, and changing their style and position. These effects can be fancy indeed, as in Dan Motzenbecker’s OriDomi, a library which enables you to fold regions on the page as if they were paper.
One of the images on the OriDomi home page, folded like an accordion
One of the images on the OriDomi home page, folded like an accordion

Given the knowledge that JavaScript can hide and reveal bits of HTML, the idea is simple. I put all the quotations into the footer one after the other. I then wrote something in JavaScript that generated a random number, revealed that quotation and hid all the others, and then repeated indefinitely. Here is a demonstration, on a stand-alone web page rather than in WordPress.

Now I’ll show the programming. Here’s the web page, with some of the quotations omitted to save space.

<html> 
<head> 
<title>Show Random Quotes</title> 
<link rel=stylesheet 
href="random_quotes.css" type="text/css"> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> 
<script src="show_random_quotes.js"></script> 
</head>

<body>

<h1>Show Random Quotes</h1>

<p>

<span class=quote-container>
<span class=quote-body>Dancing is a perpendicular expression of a horizontal desire.</span> 
<span class=quote-author>George Bernard Shaw</span>
</span>

<span class=quote-container>
<span class=quote-body>Dancing is a wonderful training for girls, it's the first way you learn to guess what a man is going to do before he does it.</span> 
<span class=quote-author>Christopher Morley</span>
</span>

<span class=quote-container>
<span class=quote-body>Through dancing many maidens have been unmaidened, whereby I may say it is the storehouse and nursery of bastardy.</span> 
<span class=quote-author>John Northbrooke</span>
</span>

....

<span class=quote-container>
<span class=quote-body>Somebody just gave me a shower radio. Thanks a lot. Do you really want music in the shower? I guess there's no better place to dance than a slick surface next to a glass door.</span> 
<span class=quote-author>Jerry Seinfeld</span>
</span>

</p>

<script>
$( function () {
     showRandomQuotes();
   }
 )
</script>

</body>
</html>

There are several important parts to the above. The first is a link to a stylesheet, which I’ll show below.

The second part is a link to the JavaScript quote generator, and another to a library called jQuery which makes it easier to create effects such as fades, and to write code that is compatible across browsers. You will notice I’ve linked to a copy at Google. I could have made a download and linked to that, but as Google say in “Google Hosted Libraries”, “The Google Hosted Libraries is a stable, reliable, high-speed, globally available content distribution network for the most popular, open-source JavaScript libraries”. For a demo like this one, that was just less trouble.

The third part is the quotations themselves. Each consists of one <span> element delimiting the body of the quotation (e.g. “Dancing is a perpendicular expression of a horizontal desire.”), and one delimiting the author’s name (e.g. “George Bernard Shaw”). Both are wrapped inside another <span>. This controls visibility: when that’s turned off, the entire quotation becomes invisible.

And the fourth part, near the end, is this:

$( function () {
     showRandomQuotes();
   }
 )
This invokes the quotation generator, but in a way that you might dub “load safe”. It’s jQuery notation for calling showRandomQuotes() in a way that ensures the page has completely loaded first, so that all the HTML that the function needs is safely in place.

Having seen the page, let’s look at its stylesheet, random_quotes.css . Its first rule, the one for .quote-container, is the only one that matters to the quote generator. It turns display of all the quotations off, leaving it to JavaScript to choose first one and then another and turn them back on. The final two rules just style the body of the quotation and the author’s name. Actually, the one that styles the body does nothing, but I’ve left it in in case I want to add to it later.

/* random_quotes.css */

/*
This file works with show_random_quotes.js 
and random_quotes.html . It styles the quotes 
and their containers as described in the 
comments below.
*/


.quote-container
  { display: none;
  }
/*
quote-container is the class for the outer 
 enclosing each quote. This initialises
it to not display. The JavaScript will override
this by fading randomly chosen quotes in and 
out.
*/


.quote-body
  { 
  }
/*
The body of the quote. Does nothing so far.
*/


.quote-author
  { font-style: italic;
  }
/*
Italicises the author's name in each quote.
*/

Finally, here is the JavaScript code. As my comments say, the important part is the function showRandomQuotes.

/* show_random_quotes.js */


/*
This file works with the stylesheet random_quotes.css
and the demo page random_quotes.html . This HTML
is a sequence of <span> elements, each containing a
quotation split into body and author. Initially, all 
the quotes are invisible, as set by the stylesheet. 
The function showRandomQuotes() below chooses a random 
<span>, fades it in, and then after enough delay for 
the user to read it, fades it out and repeats. 
*/


/* Returns a random integer between min (inclusive) and 
   max (inclusive).
*/
function getRandomInt( min, max ) 
{
  return Math.floor( Math.random() * (max - min + 1) )  
         + min;
   // Using Math.round() will give a non-uniform distribution,
   // according to the author.
   // From 
   // http://stackoverflow.com/questions/1527803/generating-random-whole-numbers-in-javascript-in-a-specific-range 
}


/* Phases randomly chosen s in and out as described
   in the comment at the top.
*/
function showRandomQuotes() 
{
  // Adapted from 
  // http://stackoverflow.com/questions/12065273/fade-in-out-text-loop-jquery

  var quotes = jQuery( ".quote-container" );
  // All the s.

  var no_of_quotes = quotes.length;

  function showNextQuote() 
  {
    var fade_in_and_out_delay = 2000;

    var reading_time = 5000;
    // Time a quote remains visible. This is long
    // enough to read the longest quote on the
    // website.

    var quote_index = getRandomInt( 0, no_of_quotes-1 );
    // Which <span> to fade in next. This index
    // is zero-based.

    quotes.eq( quote_index ).fadeIn( fade_in_and_out_delay )
        .delay( reading_time )
        .fadeOut( fade_in_and_out_delay, showNextQuote );
    // Fade the quote in, leave it for a bit, fade 
    // it out, and repeat.


  }

  showNextQuote();
  // Show the first quote.

}

In my next post, I’ll describe how I made this work within a WordPress footer.

Leave a Reply

Your email address will not be published. Required fields are marked *