A quickNnotTooDirty solution adapted and cleaned up from
this
(by the way... I found this page typing "javascript fortune" in google...)
In the head of your document add the following script
Code:
<script type="text/javascript">
function howLuckyAmIToday () {
var fortuneBox, fortunes, index, quoteText, quote;
/* Get the box where we should display the fortune */
fortuneBox = document.getElementById('fortuneBox');
/* Feed the fortunes array, add more on the same template if needed */
fortunes = new Array();
fortunes[fortunes.length] = "Our future is whatever you make it, so make it a good one...";
fortunes[fortunes.length] = "You will meet a strange person.";
fortunes[fortunes.length] = "Luck is on your side today";
fortunes[fortunes.length] = "Do NOT go in there";
fortunes[fortunes.length] = "Whatch your back";
fortunes[fortunes.length] = "You will break your leg";
/* Calculate a random index */
index = Math.floor(Math.random() * fortunes.length);
/* Create a quote element, feed the random quote in
* and add the quote to fortune box
*/
quoteText = document.createTextNode(fortunes[index]);
quote = document.createElement('q');
quote.appendChild(quoteText);
fortuneBox.appendChild(quote);
}
</script>
This step registers a javascript function that will feed a quoted fortune inside an html element having the id "fortuneBox". So the next step is to make this box on your page. At the place you want your fortune to appear:
Code:
<div id="fortuneBox"></div>
You can replace the element by 'p' or whatever box element. The important thing here is the id attribute
Last, you need to fire the function when the page loads. So modify the body element of your page like this:
Code:
<body onload="howLuckyAmIToday()">
That's it ! Now you just need some CSS rules to style your fortune as desired.
This solution will be OK for a reasonable number of fortunes. For a much larger number of fortunes, another solution might be preferable: server side script + textfile, server side script + database.... all of this being interpreted directly by your page or accessed by javascript.