CSC 105

Laboratory: Javascript for Custom Content

 

This lab will teach you to use Javascript to create pages that can vary a little bit each time they are loaded. The type of script we will use is called a load-time script, meaning that it executes as the page loads. Another type of script is called an event script, meaning that it executes in response to some event (the user clicking a button, for example). We will not look at event scripts here -- consider taking CSC 105 if you want to learn more about them!

Placing Load-Time Scripts

A load-time script is placed within the body of a document, inside a <script> tag pair. Between the <script> and the </script> there should not be any other HTML tags -- everything inside should follow Javascript rules and syntax. You can place content in your page using the document.writeln command:

<script type="text/javascript">
document.writeln("<p>This paragraph will appear inside the document.</p>")

</script>

Of course, so far there's not much point, since you could include this paragraph in your document directly without much trouble. We need some way of getting variable content.

Variables

A variable is a container that can hold some arbitrary value. Alternately, if you have a value you want to keep track of (say, a response entered by the user) you can think of the variable as a name associated with that content.

Try adding the following lines to the script above, and load the page in a web browser. (Dreamweaver doesn't execute scripts even in the design view, so you cannot test it there. However, clicking the icon that looks like a miniature globe will automatically save the web page you are working on and open it in a web browser.) Can you explain what happens? (Here's a page that shows how yours should work.)

var userName = prompt("What is your name?")
document.writeln("<p>Hello, "+userName+"!</p>")

Try it!

Write a simple Mad Libs page. It should ask the user for at least three different words (noun, verb, adjective, etc.) and create a custom story using each of the words one or more times.

A Challenge

If you found the above too easy, try this challenge: make a page that has a randomly chosen background color. You already know most if not all of the tools you will need to do this. Think about how background color is normally set in a page, and use a script that will produce this as content at the appropriate point in the page. You will probably want to use this sort of expression to generate some random numbers:

var red = Math.floor(256*Math.random())

Javascript also has functions to convert integers into hexadecimal strings:

var red2 = red.toString(16);

(The 16 here refers to base 16, i.e., hexadecimal. It modifies the normal behavior of the toString command, which would normally give you a standard decimal representation.)