Adding a Random Quote to your Static Blog with Javascript - Web Tutorial

Understatement
By Andrew Davidson
on April 15, 2020



Having to update a daily sidewalk sandwich board (seen above) to keep the local pedestrians entertained (and possibly remind them that they should be bringing their digital conversions to my office as well), you need to keep a nearby cheat sheet of clever phrases and quotes that one can call upon at a moments notice for creative inspiration.

Initially, I had a multi-page Google Doc with line after line of funny quotes, but missed out on being able to add source links, hashtags and metadata. So I converted it to a Google Sheet, with different columns for additional data, and so begins the upward trend of turning this meager text file into a full fledged database.

I'm unhappy with the frequency that I can update my sign, which currently is not at all as I'm forced to be closed by both the state and city due to the Coronavirus, and am planning on maintaining the quarantine until at least July 1st. So many missed days of business in center city Philadelphia! Our hilarious puns and one-liners needed a place to shine and be appreciated! Thankfully my website is ever growing and has plenty of places to sneak in one of my classic 'Stingers' and celebrate my weird punny humor.

I'm quite familiar with web development, and there's plenty of ways to achieve this function, but I wanted to do it simply, and with no overhead of a massive library doing functions. I prefer well documented, plainly written and step-based code that can be copy-pasted with only the slightest of changes to make it work easily for you. This particular bit of javascript code is based heavily on this Stack Overflow question which got me started.

Alas, there is a caveat to running this code: your text-file database will have to be on the same web server that you're calling the script from. While it can be configured to work across different domains, it's a cross-site security issue that's easier avoided by simply hosting your own text file. This assumes you have access to your web server and can upload text files to a publicly accessible location on the same domain you're posting from. This does not apply to Facebook, Medium or WordPress.com sites, but YMMV.

Here's my local text file database of stingers or you should make your own (mine sways from extremely adult to childish). Since my list has over 3000 lines, it's a bit of a load at 245kb, but it's basically the size of a large image, so it doesn't weigh to heavily on the page weight, if you ask me. The text file should have carriage returns between each line, and is exported and filtered from my master spreadsheet, as it removes the extra metadata that it unneeded in this application. This is also randomly sorted ahead of time to add another level of randomness to the output.

With this file in place on my web server, all I need to do is insert this tiny bit of HTML and Javascript somewhere in my HTML templates to have it silently insert a random 'Stinger' from my many thousands:

<p>Random Stinger: <strong id="stinger"></strong></p>
<script>
var stinger = new XMLHttpRequest();
stinger.onload = function() {
    // load the text file contents
    var step1 = this.responseText;
    // split into individual lines by line break
    var step2 = step1.split('\n');
    // pick a random line number from acceptable values
    var step3 = Math.floor(Math.random() * step2.length);
    // extract the value of that line
    var step4 = step2[step3];
    // add the random line to an ID
    document.getElementById('stinger').innerHTML = step4;
};
// the local url of the text file
request.open( 'GET', '/src/stingers.txt', true );
request.send();
</script>

The first line is the HTML that gets inserted into the source file of each HTML document where I want my 'Stingers' to appear - in this case, wrapped in a <p>aragraph tag. In this case, it's proceeded by the words 'Random Stinger:' and the Javascript inserts the random selection into the 'strong' element that has the 'stinger' ID - this way I get to bold the results without having to add a new class to my stylesheets.

The text lines that begin with the double back-slashes (//) is not code, but programmer comments, to explain what the line below it is doing. They are ignored by the javascript processor, they are for human-readable information only. You may remove the commented lines from your own code to make it slimmer. The request.open line has the URL of the text file database, as a relative link. You'd change it to your own file at it's own location on your own web server.

I've included it on every blog post in 2020 (it's just under the copyright notice in the footer below), and will maintain it for all upcoming posts, and hopefully find time to add it to older posts as I find time to do some major HTML editing. If you happen to be one of those View Source... people, you'll note our live version calls a external javascript file, and is not inline like our above example.

Reload this page to see it update again and again.

Thanks to Stack Overflow for the inspiration, and TinyJPG, who easily shaved 55% off our images, making this page load fast!