Random Story Using Javascript

Written By: John Fawcett

- 20 Mar 2006 -
















Description: Create 3 different stories, with a headline, picture, and actual story, and randomly display them one at a time on page load.

  1. Creating the Story
  2. Write the Variables

Write the variables

Ok, so we've gotten all our variables coded out and corresponding to each other. How do we get them on the page? We must use a combination of "if" and "then" statements and another object and method. Here they are:

if (ran_num==0)
{
        document.write(';'+title[ran_num]+'
[ran_num]+'" border="0"> '+story[ran_num]+'
') }

What's going on here you ask? I'll explain, unfortunately. It's saying if the variable ran_num is 0, then write that is between the ('') to the document. I just used a simple html table to format the entirety of the story. If you look at, It's basically HTML, except where I want my variable, I stick them there except all my Javascript variables are in these '+var+'. Notice all my HTML code uses parenthesis, before, in my other variables, we couldn't use regular parenthesis. Now we can, because inside methods, we use apostrophes to start off and when we end.

NOTE: The code for the if and then statement is just for the first story. You'll have to add new ones for the other two stories. They'll be the exact same code, except (ran_num==1) and (ran_num==2).

Here's the whole code

 

That's what it should look like, minus word wrap. Make sure you save your file with .js file extension.

Now to place it your HTML, simply stick the following code where you want it in your page.

AND YOU'RE DONE!

Next >>