Fortune Teller

Once you get the hang of basic Javascript and arrays, this knowledge can be put to use in many, and sometimes strange, ways. In this lesson, you are going to learn how to create a basic fortune telling application with just a few lines of code.

  1. Create a basic HTML document and name it fortune.html or something else appropriate.
  2. Add an input text field to the body of your document as shown,

  3. Add a div tag below the field.  Give it an id of  result. 

  4. Because the Javascript for this lesson is so short, simply add <script> </script> tags at the bottom of your html document, after </html>.
  5. Between the <script> tags create a string array with at least five outcomes named outcomes. Here is an example:

  6. On the next line create a new function named fortune like this:
    function fortune() {            } .
  7. Add a few lines between the brackets of your function.
  8. On the first line of your function, create a variable named 'name' and tie it to the value of the #namehere textfield as shown below.

  9. Our next task is to create a random number generator that we can use to pick one of those fortunes, well, randomly.


    In case you are interested, Javascript has a random number feature (Math.random) that generates a value between 0 and 1. Here we multiply that value times the length (number of values in) the outcomes array. Then we use math.floor to round that value down to the nearest integer (whew). In any event, we end up with a random integer that ranges from 0 to the number of items in the array minus 1, which is exactly what we need!

  10. On the next two lines we create a variable named result and tie it to the #result div tag where we display the fortune. Then we set the html of result to the name that is entered into the text field, plus a bit of feedback, plus the random fortune that comes out of the array.

  11. Now add a button that calls the fortune function

    and test everything. 

  12. Once you get it to work, your job is to make it look good. Crystal balls come to mind..... Have fun!