Lesson 7: Add a quote of the day!|
Lesson 7: Add a quote of the day!
Learn to make a random quote of the day.
View the demo to see the result.
Since you now are an expert on using files after lesson 4
(the Guestbook), let's make something a little bit more fancy. I often see people having a
"tip of the day", or a "quote of the day", and I thought I should try to make
a VBScript variant. It reads the quotes from a text file (for easy maintenance),
and displays it.
Let's start coding! First make a text file in a directory.
Fill it with your quotes, one on each line.
To make it easier later on, add the number of quotes (lines)
on the first line (alone). Now your text file will look something like
A Computer Scientist Is Someone Who Fixes Things That Aren't Broken.
Any Sufficiently Advanced Bug Is Indistinguishable From A Feature. -- Kulawiec
Asking Whether Machines Can Think Is Like Asking Whether Submarines Can Swim.
Why the number? Well we are to pick a quote at random, and
we therefore need to know how many quotes there are. We could
just loop trough the file one time, counting home many lines
there are. But to make it a little bit faster, we use a header.
And now to the script:
'First we open the banner file, make sure you have the right path to the file
Set MyFileObj = Server.CreateObject("Scripting.FileSystemObject")
Set MyTextFile = MyFileObj.OpenTextFile("c:\quote.txt")
'Then we read the header
IF NOT MyTextFile.AtEndOfStream THEN
header = CInt(MyTextFile.ReadLine)
'Then we make a random value based on the header, the RANDOMIZE
'statement is important to insure a random value.
LowestNumber = 1
HighestNumber = header
RandomValue = INT((HighestNumber-LowestNumber+1)*Rnd+LowestNumber)
'Loops until it comes to line number=random value
'And then it saves it in the variable quote
WHILE NOT MyTextFile.AtEndOfStream AND NOT Count = RandomValue
quote = MyTextFile.ReadLine
Count = Count + 1
'Closing up the text file
Today's quote is: <%=quote%>
Download the code: Lesson7.zip
Use this script in an include file, and use:
where you want the quote to appear. For more info on using
INCLUDE, see lesson 6.
Where to go next:
Take a look at our lessons page
to get an overview of all our lessons.