I hope this blog is useful to anyone who wants to incorporate a random motivational quote or ‘tip of the day’ message into their projects. I attached a sample .cptx file as well. randomQuotes
Step 1: Write the Quotations in an Array
The hardest part about creating any random quote generator is finding, copying and pasting the actual quotes. Luckily there are lots of websites such as textfiles.com that could help you out – that’s where I got this file. Your array must be in the following format:
var cmt = [
“quotation 1”,
“quotation 2”,
“quotation 3”,
“quotation 4”
];
If you have 100’s of quotes, you want to make sure that each starts and ends with a proper quotation mark. There should not be quotation marks anywhere else. Each quotation is separated by a comma. There should not be a comma on the last quote.
Step 2: Test your Array
You can paste your javascript array into the ‘on enter slide execute javascript’ window of your first slide. Preview your project in a web browser and press F12 (if you are using Chrome) to enter the console screen. If there are no errors you are off to a great start.
In this example, I named my array ‘cmt’. Type the name of your array into the browser console. This should return the text of your entire array. Now type:
cmt.length
This will return the number of quotes (items) in your array. In my example it returns 40. Now type:
cmt[4]
This will return the quote in the 4th position. (Arrays start at 0)
Step 3: Generate a Random Number
We now need is a random number between zero and the total length of the array. At this point I could just say 40 but what if I wanted to add more quotes to my array one day. For this we use the following in our javascript window.
var rnd = Math.floor(Math.random() * cmt.length);
This creates a new variable called rnd. It uses Math.random to generate a number between 0 and ‘cmt.length’ which is the total length of the array.
Step 4: Create the Text Box
On your slide create the textbox. Have it show a variable called ‘quote’ – make sure you change the maximum characters to something large like 50000. In your javascript window enter the following:
comment = cmt[rnd];
This means that the variable ‘comment’ will equal a comment in our array ‘cmt’ that falls at our random number [rnd].
If you want a new random comment, you can create a button and again execute:
var rnd = Math.floor(Math.random() * cmt.length);
comment = cmt[rnd];