(Updated: 2005/09/23, 11:45 )

JAVA Script: Web Page Design

 

Created by: Shelly Zhao 

Updated by: Tanya Ellchuk

Updated by: Holger Hoos

Updated by: Billy Cheung

Comments to: Steve Wolfman


Sources: some of the  lab was taken from:



Contents

 



Objectives

In this lab you will be introduced to a new method of creating and enhancing internet web pages -- JavaScript. 

You will get an introduction of how JavaScript is used in page design, and will be able to add some advanced features into your web pages using JavaScript. By now, you're probably asking: "What is Javascript, and why do I need it?" Although we will get into some detail over what it is later on, right now, consider it a way to give life to your webpage by allowing you to inject components into your webpage that changes depending on how the person viewing your page interacts with them!  



Lab Overview

We will cover these topics in the lab:

  1. JavaScript Overview
  2. JavaScript Essentials
  3. Mouseover
  4. Quiz
  5. Advanced Feature (Optional)
 

Before the Lab

Before the lab you should have met all the requirements of the HTML Web Page Design lab.



During the Lab   

NOTE: 

1. JavaScript Overview

This section of the course will bring you up to speed on the basics of JavaScript.  We will take a look at some important facts about JavaScript that all aspiring scripters need to know, and then we'll dive right in with a quick example of a simple JavaScript.

 
If you have written any JavaScript at all, you might wish to skip the first example.  It contains a very simple script that is meant to show some of the basic syntax common to all JavaScripts.

1.1 JavaScript is Embedded inside HTML

One of the most distinguishing facts about JavaScript is that it is embedded inside HTML. JavaScript is (almost) never seen on its own when you surf the net. All client-side JavaScripts (meaning JavaScripts that affects the person viewing the webpage) are placed either inside the <head> </head> or <body> </body> tags of an HTML document.

In fact, without HTML, JavaScript will not have a user interface.  HTML and your browser provides JavaScript with access to the user.  However, HTML isn't doing all the work either.  JavaScript extends the capabilities of almost every HTML tag by allowing them to respond to events, something that we will look at closely in upcoming sections.

We will explain the JavaScript code later, but this is a simple example of JavaScript being embedded inside HTML. To try it out, simply create a new .html file, and copy and paste the following code in it:

<html>
<head>
<title> My First Script </title> 

<script type="text/javascript">
<!-- 

    alert("This is an alert button; click it in order to see the normal HTML page.");

// -->
</script> 
</head>

<body>
<h3>Normal HTML code goes here, as you've learned in the HTML lab.</h3>
</body>
</html>

The JavaScript in this example is in BOLD.

1.2 JavaScript is Browser-Dependent

JavaScript code is not only dependent on HTML, but it is also dependent on the user's web browser. Unlike the Java code you will learn about later(which can pretty much be run anywhere and any time), JavaScript can't 'do' anything on its own, and is run only when the browser open the webpage.

JavaScript support is provided by all modern browsers, including Firefox and Internet Explorer, regardless of which type of operating system they run on. JavaScript owes much of its popularity to this fact; it saves you, the developer, a lot of hassle. The code is interpreted(read and understood) by the browser only when the page containing the code is loaded, much like the way HTML tags are translated during the loading of the page. Like HTML, JavaScript code is written in plain text. The same code that runs on Firefox or any other JavaScript-enabled browser on your PC will run on any other platform, as long as JavaScript capable browsers are available for that platform. This means that the webpage you open with Internet Explorer while you are running Windows will look the same when you open it using your Mac's IE. However, there are certain times when a browser will, for one reason or another( be it security, antiquity, etc.) not have scripting support. In those cases, if you want to let the user know that they are missing out on something, you can use the noscript tag. So for our previous example, we can change it to:

<html>
<head>
<title> My First Script </title> 

<script type="text/javascript">
<!-- 

    alert("This is an alert button; click it in order to see the normal HTML page.");

// -->
</script> 
  <noscript>Your browser does not support JavaScript!</noscript> 
</head>
<body>
<h3>Normal HTML code goes here, as you've learned in the HTML lab.</h3>
</body>
</html>

Note that the text in the noscript tag will only be seen if the browser can't run the script.

2. JavaScript Essentials

It's time to jump right in and look at your first JavaScript! Although this is a simple example, it will show you the essentials that will go into every JavaScript you will write.

Add the following bold part into the head of your "courses.html"

<html>
<head>
<title> UBC Courses </title> 

<script type="text/javascript">
<!-- 

    alert("You are entering my UBC course page. Go ahead, click OK.");
	
// -->
</script> 
</head>

<body>
......
</body>
</html>

Now go to your "main.html" and click on the link to the "courses.html" to see what happens. Click here to see what it should be. 

Great!  You've now seen your first JavaScript.  Let's dissect the code and take a look at some of the essentials of every JavaScript.

2.1  Places of JavaScript

The JavaScript here is contained within the <head> tag and the </head> tag.  This is where most of your JavaScript will go, but there are times when you'll find JavaScript between the <body> tag and the </body> tag.  We'll explore that further when you get into event handling, which, as the name implies, is how you can make your web page reaction or handle events(actions) done by whoever is browsing your site.

<html>
<head>
<title> UBC Courses </title> 

<script type="text/javascript">
<!-- 

    alert("You are entering my UBC course page. Go ahead, click OK.");
	
// -->
</script> 
</head>

<body>
//JavaScript can also be in here too.
</body>
</html>

2.2 The <Script> Tag

The first thing you see within the <head> </head> area is <script type="text/javascript">.  This tells the browser that everything between that tag and </script> is JavaScript code that has to be interpreted.  

...... 
<script type="text/javascript">
......
</script> 

2.3 The <!-- and //->

The strange symbols <!-- and //-> need to surround your JavaScript within the <head> and </head> tags.  As all good programmers know, it's generally a good idea to comment whenever possible. Every line that starts with // is a comment until the end of the line. <!-- and --> are the same constructs used for HTML comments; they hide JavaScript from browsers that don't support it.  Just remember that these two strings should surround all of your JavaScript code in your <head> section, right inside the <script type "text/javascript"> and </script> tags.

......
<script type="text/javascript">
<!-- 

    alert("You are entering my UBC courses page. Click OK.");
	
// -->
</script> 
</head>
......

2.4 The alert() Method

Finally - something interesting!  alert() is one of JavaScript's most frequently used methods. A method is just object-oriented talk for something that performs an action on an object; in this case, the object is your browser's window. So, just think of methods as keywords that does the same thing everytime you use them. For example, if the Bob() method adds 1 to some number, then the first time I call Bob(), the number will be increased by 1, and when I call Bob() again, it will be increased by 1 yet again.

alert() is a great way to get a user's attention.  It issues a curt beep on sound-equipped systems and displays a message of your choice in a special pop-up box.  Like in many other programming languages, strings(of text) in JavaScript are enclosed in quotes and the semi-colon at the end of the alert() line signifies the end of a JavaScript statement.

......
<script type="text/javascript">
<!-- 

    alert("You are entering my UBC courses page. Click OK.");
	
// -->
</script> 
</head>
......

3.Mouseover

The mouseover is probably the most used JavaScript trick, and almost every JavaScript enabled page makes use of it in one way or another.  Maybe you have seen a menu that seems to come to life when you move the mouse over the different menu items - the mouseover in JavaScript is what makes this possible.

The mouseover is also often called an imageswap or image rollover, since that is exactly the action JavaScript performs. When you move your mouse over a menu item, JavaScript reponds by swapping the original image with another image of your choice.

Now, change the image of your picture in the "main.html" by typing the following, and see what happens when you open it with a browser.  Be sure to roll your mouse on and off your picture. Click here to see how it should work by moving your mouse over the picture of the monkey. 

<P>
<A HREF = "#" onMouseOver = "document.images[0].src = 'logoUBC.jpg';"
onMouseOut = "document.images[0].src = 'mypicture.gif';">
<IMG border=0 SRC = "mypicture.gif" width="95" align="left"></A>
<P>

Although the code is extremely short, it introduces two very important and fundamental concepts of JavaScript. The mouseover is made possible by the client-side object hierarchy and the event handling of JavaScript.  As you learn more JavaScript, you will find that understanding these two concepts are absolutely essential to writing useful JavaScripts. Basically, client-side object hierarchy is just how Javascript describes wherever it is being run on. In this case, the browser. 

We can start by dissecting the code from this example.

Here is the line that makes the image swap possible:

<A HREF = "#" onMouseOver = "document.images[0].src = 'logoUBC.jpg';" onMouseOut = "document.images[0].src = 'mypicture.gif';"><IMG border=0 SRC = "mypicture.gif" width="150" height="100" align="left"></A>

A few things are happening here, so let's look at one part at a time.  Everything that is not in bold is just straight HTML that places and aligns an image on the page.

JavaScript is trapping two different events here.  Most of the JavaScript code that you will write reponds to events caused by the user or the web browser.  "onMouseOver" detects when the mouse cursor is moved over a certain area(in this case our image, though you can use it for links and such as well), and "onMouseOut" detects when the mouse cursor is moved away from the image.  

As mentioned before, JavaScript is tightly integrated with HTML, and the power lies in its ability to give HTML tags "intelligence" - or a way to respond to user interaction.

onMouseOver = "document.images[0].src = 'logoUBC.jpg';"

Everything between the quotes is active JavaScript.  In English, this says, "When the mouse is moved over this image, change the file source of the first image in the document (this one being the first) to 'logoUBC.jpg'."

Notice the dot notation refers to objects lower in the object hierarchy, and the square brackets which access different elements in an array; in this case, the array of images that are part of this document Think of it this way. The dot notation represents a part or attribute of the object(so here we are finding the document's image's source). Consider all the images in a document to be stored in a container(an array), so in order to refer to the first one, we would look for images[0]. Likewise, the second one would be images[1], etc. (We start from 0 instead of 1).

 

4. Quiz

Here is an example, "wmst201quiz.html", of how to create a quiz in JavaScript. Re-save it with the file name "quiz.html". You will also need this file, save it with the name "quiz_result.html".

Note: The goal of this section is to modify the quiz to contain your own questions (and answers). At the end of the lab, you should have a quiz with at least two of your own questions and none of the questions from the original example quiz.

4.1 quiz.html

Open the file "quiz.html" with Notepad, and find the following line near the beginning of the file:

form name=wmst201quiz method=get action=wmst201quiz_result.html

Change the form name from "wmst201quiz" to "myquiz" , and the action from "wmst201quiz_result.html" to "quiz_result.html". (Do not include the quotes). What we are doing here is telling the JavaScript that the name of our form is now myquiz(since we renamed it from wmst201quiz) and likewize, we will be using quiz_results.html now when we call the get action(when we grade the quiz)

Also, find the questions, so that you can change the content of the quiz.

The html code for the questions is like this:

<TD colSpan=4 height=25>What do you use to browse an HTML file? </TD></TR>
  <TR>
    <TD height=24></TD>
    <TD height=24><INPUT type=radio value=0 name=2> Word</TD>
    <TD height=24><INPUT type=radio value=1 name=2> &nbsp;Excel</TD>
    <TD height=24><INPUT type=radio value=2 name=2> &nbsp;PowerPoint</TD>
    <TD height=24><INPUT type=radio value=3 name=2> &nbsp;Internet
  Explorer</TD></TR>
  <TR>

Where you can change the question "What do you use to browse an HTML file?" to your own question.

Each question will have four answers, shown as "Word", "Excel","PowerPoint" and "Internet" in above example. Also try to change the answers according to your questions, and do not touch other format settings.

4.2 quiz_result.html

Now open the file "quiz_result.html". Read carefully the text between /* ....... */ before each part of the JavaScript function. 

Here is the copy of the explanations:

1) the JavaScript in the <head> is function handleQuestion:

/* the handleQuestion function
 *
 * This function figures out what answer the user chose for the question with 
 * number 'questionNumber' then prints the question and the correct answer. 
 * It is important that this function is called for each question in order.
 * You don't have to change the code here.
 */

2) The second JavaScript code is in the <body>:

/* This code creates the output page after the user submits some answers. 
 * Put your four answers to each question to answer[1] to answer[4], and
 * set the variable 'correct' to be the number of the correct answer.
 *
 * good luck in your quiz. 
 */

NOTE:

5.. Advanced Feature (Optional)

This part is just to demonstrate some fancy things that JavaScript can do. Only examples, not how to create the code, are given for each topic.

Here are some examples that you can put into any of your pages. Feel free to change them or to find other examples on the web. You can use the links at the end of the lab as a reference.

5.1 Multiple images swap

5.2 Prompt windows

5.3 Login and Password (enter "cpsc101" as the UserID and password)

5.4 Length Conversion Calculator

Also, there are sometimes situations where you might want to use the same JavaScript again without wanting to retype the entire thing. In those cases, you can simply use:

<script src=Name of your Javascript file></script>

in place of the

<script type = "text/javascript"> Your scripts </script>



Deliverables
  1. At the end of your "main.html" file, make sure that there is a link to your "courses.html" and "quiz.html" web pages. Add a one-sentence summary description of each page above or below your link.
  2. Publish your final "main.html", "courses.html", "quiz.html", and "quiz_result.html" pages in your computer science ugrad web site as you did in the previous HTML lab. Make sure all of the links work properly.
  3. Grading scheme for this lab: alert button: 2 marks, mouseover: 2 marks, quiz (with 2 or more questions): 2 marks, one-sentence summaries (of "courses.html"and "quiz.html") in "main.html": 2 marks, links to "courses.html" and "quiz.html" working from "main.html": 2 marks


Reference Links
  1. http://www.a1javascripts.com/
  2. Doc JavaScript -- JavaScript Tutorials, JavaScript Tips, and JavaScript Tools
  3. Java.sun.com
  4. Web Monkey
  5. Examples of bad websites.

It is more challenging and fun to search professional Web pages to find out what JavaScript can do. Try the reference links above,  and add one of the more interesting features into any of your three pages. You need to have a separate link in your main page to specify what the function is and where you found it, what you did to revise it, and where you put it.