

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
How to write a simple javascript code to display a randomly selected quote from a list on a webpage. It covers creating an array of quotes, selecting a random integer, and writing the quote to the html document.
Typology: Exercises
1 / 2
This page cannot be seen from the preview
Don't miss anything!
COMP 519 Web Programming
JavaScript: Random quotations
How can you write a simple JavaScript to display a randomly selected quote on a webpage? This will be from a list that you specify. Probably the first thing to do in the script is to declare a new array variable like:
var quotes = new Array(); Then you can load the array with quotes of your choice. You should insert them sequentially so that there will be no gaps in the array (otherwise the array value will be undefined if you were to try to print it out). Note that you should enter the quotes as a single line, but for space reasons they’re given over multiple lines here.
quotes[0] = "Hey, you can’t fight in here! This is the war room!
- Dr. Strangelove"; quotes[1] = "He who fights fire with fire burns his house down twice as fast.
- Vietnamese proverb"; quotes[2] = "I have not yet begun to fight.
Then having selected a random integer, you can use the document.write command to write it to the HTML document.
Easy, huh? You can insert your code into any document, or you can save it to a separate file and insert it in your HTML code in the manner I described in class. A fully working JavaScript function is shown on the next page.