What We Will Cover
Elucidations
Reminders
Homework Questions?
Homework Discussion Questions
- Have any students worked with CSS before?
- How does CSS make formatting Web pages a simpler and more robust activity?
- When would you use an in-line style versus an embedded or external style?
- What challenges do new forms of media present to Web developers?
- How can CSS help meet thee challenges?
^ top
4.1: Introduction to JavaScript
Learner Outcomes
At the end of the lesson the student will be able to:
- Discuss the history and theory of JavaScript
|
^ top
4.1.1: About JavaScript
- JavaScript was developed by Brendan Eich while working at Netscape
- Netscape released JavaScript in Navigator version 2.0B3 in December of 1995
- Microsoft added support in IE version 3, released in August 1996, for their version of JavaScript which is called JScript
- Since multiple browsers were supporting JavaScript, Netscape submitted the specification to a standards organization: European Computer Manufacturers' Association (ECMA)
- Standardized as ECMA-262 in 1997
- Officially known as ECMAScript
- However, most people still call the language JavaScript
- Since then, both Netscape and Microsoft have continued to add extensions to the standard language
- In the last few years, however, Mozilla has taken the lead in JavaScript development from Netscape
- For instance, Firefox has added support for E4X, an extension that adds native XML support to ECMAScript
Brief History of JavaScript
| Version |
Date |
Browser Version |
| 1.0 |
1995 |
Netscape Navigator 2.0 |
| 1.1 |
1996 |
Netscape Navigator 4.0 |
| 1.2 |
1997 |
Netscape Navigator 4.0 |
| 1.3 |
1998 |
Netscape Navigator 4.5 |
| 1.5 |
2001 |
Netscape Navigator 6.0 |
| 1.6 |
2005 |
Firefox 1.5 |
| 1.7 |
2006 |
Firefox 2.0 |
Brief History of JScript
| Version |
Date |
Browser Version |
Approx. JavaScript |
| 1.0 |
1996 |
Internet Explorer 4.0 |
1.0 |
| 4.0 |
1997 |
Internet Explorer 4.0 |
1.3 |
| 5.0 |
1999 |
Internet Explorer 5.0 |
1.5 |
| 5.5 |
2000 |
Internet Explorer 5.5 |
1.5 |
| 5.6 |
2001 |
Internet Explorer 6.0 |
1.5 |
JavaScript is Not Java
- The last minute name change of LiveScript to JavaScript has resulted in years of confusion
- There is no real relationship between Java and JavaScript
- Java is a programming language developed by Sun Microsystems (vs. Netscape)
- JavaScript was designed as a language for web browsers
- Java is a general-purpose language like C++
- JavaScript is a scripting language with easier to use, but more problematic, language features
- A scripting language is designed to be easy to use for small programming projects
- However, it becomes much harder to use scripting languages for large programming projects
More Information
^ top
4.1.2: What Can JavaScript Do?
- JavaScript was designed as an easy way to add interactivity to HTML pages
- Since its inception, JavaScript has become the default browser scripting language
- Let us look at some of the things you can do with JavaScript
- We will explore many of these during the course
Some JavaScript Capabilities
- Validate the data users enter into forms
- Perform calculations
- Manipulate the HTML Document Object Model (DOM)
- Change the browser itself or even create new browser windows
- Create different content for different users
- Randomly display different images
- Play sounds
- Create animations
- Make online games
- Respond to events (like mouseovers) to make your Web pages "come alive"
^ top
4.1.3: Case Study: Hiding E-Mail Addresses from Spammers
- To introduce you to the language, the textbook provides a case study on using JavaScript to hide email addresses from spammers
- Some terms and definitions:
- Spam: Junk email
- Spammer: Person who sends spam
- Email harvester: Program that scans documents looking for email addresses
- As the Internet has evolved, spammers, email harvesters and other intrusive programs have looked to take advantage of the Web
- Because of this, you want to be careful when putting email addresses on a web site
- Email harvesters work by scanning web pages and looking for text that looks like an email address
john.smith@nowhere.net
- When they find a match, they add the email address to a database
- Spammers use these email databases to send out their spam messages
Listing Email Addresses
- The problem for the case study is how to list email addresses that are hard for spammers to harvest
- You can look at the problem by following the link: Monroe Public Library
- Note how the email addresses are missing from the Staff Directory
- Our job is to display the email addresses in a secure manner
- JavaScript can help us protect email addresses from email harvesters
- To do this, we want to list the email addresses in the web page in a scrambled way
- Then we want to use JavaScript to unscramble the addresses when people look at the page
Staff Directory Web Page
^ top
4.1.4: Server-Side and Client-Side Programming
- Before we can solve the problem, we need to look at how web programming works
- Web programming comes in two types:
- Server-side programming
- Client-side programming
Server-Side Programming
- Server-side programming puts the programs on the server that hosts the web site
- The program can modify the content and structure of Web pages
- This is shown in the following diagram
- We will look at how to do this type of programming toward the end of the course
Client-Side Programming
- Client-side programming runs programs on user's computer
- Programs likely to be more responsive to users
- However, can never completely replace server-side programming
- This is shown in the following diagram
Combining Client-Side and Server-Side Programming
- You can combine client-sided and server-sided programming
- This allows you to take advantages of the strengths of both types of programming
- This is shown in the following diagram
^ top
4.1.5: Summary
- JavaScript was first released in the Netscape Navigator 2 in 1995
- Microsoft released a version of JavaScript, called JScript, in IE 3 in 1996
- Since multiple browsers were supporting JavaScript, Netscape submitted the specification to a standards organization: European Computer Manufacturers' Association (ECMA)
- Because of this, JavaScript is officially known as ECMAScript
- However, almost everyone still calls it JavaScript
- All the major browsers support the ECMAScript standard but add extensions
- If the extension become widely used, then they eventually get added to the standard
- JavaScript is not Java and has no real relationship to Java
- JavaScript is a scripting language designed to be easy to use for small web-programming projects
- Even though JavaScript is easy to use, it has many capabilities
- We saw a list of some of those capabilities
- We also looked at how web-programming works
- Web programming comes in two types:
- Server-side programming, which puts the programs on the server that hosts the web site
- Client-side programming, which runs programs on the user's computer
- You can combine client-sided and server-sided programming
- This allows you to take advantages of the strengths of both types of programming
Check Yourself
- Who invented JavaScript and when was it released?
- Which browsers support JavaScript?
- Is there a standard JavaScript? Is so, what is the standard?
- Why was JavaScript invented?
- What task is JavaScript designed for?
- What is a client-side program?
- What is a server-side program?
^ top
Activity 4.1
Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.
Quick Quiz
^ top
4.2: Creating Scripts
Learner Outcomes
At the end of the lesson the student will be able to:
- Create a script element
- Code basic JavaScript syntax
- Write text to a Web document using JavaScript
|
^ top
4.2.1: Working with the Script Element
- JavaScript can be placed either directly in HTML or in a separate file
- We will first look at adding JavaScript directly to an HTML page
Creating a Script Element
JavaScript Statements
- Statements are the commands you give a computer in a program
- One of JavaScript's many statements is:
document.write(something);
- JavaScript has many scripting statements, also known as JavaScript commands
- The
document.write() method is one way to send output to a web document
- The first part of the statement,
document, is known as an object
- The second part,
write(), is known as a method
- The statement ends with a semicolon (;)
- An object in the real world is some item that you can select and interact with
- In programming, we simulate real-world objects using a programming language
- We select the object using its name, such as
document
- We interact with the object by calling a method, such as
write()
^ top
4.2.2: Understanding JavaScript Rules and the Use of White Space
- Besides using semicolons to end statements, there are other JavaScript rules you need to know
JavaScript is Case Sensitive
- First of all, JavaScript is case sensitive
- That means that the following are NOT the same:
document.write("Hi");
Document.write("Hi");
- The first line writes "Hi" to a web page
- The second line means nothing to a browser and will cause an error
JavaScript Ignores Most Extra White Space
- Like HTML, JavaScript ignores most occurrences of extra white space
- This means that you can add extra spaces in your code to make it easier to read
- However, there are some cases where line breaks will cause problems
- Line breaks cannot be placed in statements anywhere you cannot have spaces
- Also, you cannot have line breaks in the middle of quoted strings
- For instance, the following will cause an error:
document.write("This is an example
of how a JavaScript error
occurs due to incorrect line breaks.");
- If you need to break a long line, you can indicate that the statement continues on the next line by using a backslash (
\)
document.write("This is an example \
of how a JavaScript error \
occurs due to incorrect line breaks.");
- The following code shows the error
- To see the error in Firefox, you will need to open the JavaScript Console from the Tools menu
- To see the error in IE, you first need to install and enable the Script Debugger tool
Example File with a JavaScript Error
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>JavaScript Error Demonstration</title>
<script type="text/javascript">
document.write("This is an example
of how a JavaScript error
occurs due to incorrect line breaks.");
</script>
</head>
<body>
<h1>JavaScript Error Demonstration</h1>
<p>This page has an error in the JavaScript.</p>
</body>
</html>
|
See the example
^ top
4.2.3: Supporting Non-JavaScript Browsers
1
2
3
4
5
6
7
8
|
<script type="text/javascript">
document.write("Hello world");
</script>
<noscript>
<p>This page requires JavaScript. Please turn on
JavaScript if your browser supports it and reload
the page.</p>
</noscript>
|
^ top
4.2.4: Supporting JavaScript in XHTML
- Using JavaScript in XHTML can cause problems
- The issue is that XHTML parsers try to parse the symbols in JavaScript
- Since JavaScript often contains symbols such as angle brackets (
< >) and the ampersand (&), a validator may reject the page
- To avoid this, you can place your JavaScript code in a
CDATA section
CDATA Section
^ top
4.2.5: Summary
Check Yourself
- What element do you use to add JavaScript to HTML code?
- What is a statement? A command?
- What is an object?
- What is a method?
- What JavaScript would you use to write the text "Public Library" as an
h1 heading?
- What JavaScript would you use to write the following tag?
<h2 id="sub">Public Library</h2>
- How do you enter a single JavaScript statement on two lines?
^ top
Activity 4.2
In this activity we write text to a web page using JavaScript.
Specifications
- Save the following files to a convenient place on your computer like the Desktop:
- Complete the instructions in Figure 1-9 on page JVS 10 of your textbook.
- If you have difficulty, please ask a classmate or your instructor for help.
^ top
4.3: Working with Variables and Data Types
Learner Outcomes
At the end of the lesson the student will be able to:
- Declare a variable and assign it a value
- Reference a variable in a JavaScript statement
- Describe the different data types supported by JavaScript
|
^ top
4.3.1: Introduction to Variables
- A variable is the name of a location in a computer's memory
- In this location you can store numbers and text strings
- However, you can only store one value in each variable
- Values stored in a variable can change (vary) as the program runs
Variable as a Container
- You can think of a variable as a container like a CD jewel case
- Each case can hold only one CD at a time
- You can label the case with a name like:
mystuff
- You can put CD's in a case and take them out again
- You can reuse the case many times
^ top
4.3.2: Declaring Variables
Naming a Variable
- A variable name is a sequence of letters, numbers, or underscore characters
- However, JavaScript has some limitations on variable names
- Specifically, the first character must be either a letter or an underscore character (
_ )
- Also, the variable name cannot be one of JavaScripts reserved words (keywords)
- For a list of reserved words, see: Reserved words in JavaScript
- Note that you cannot have spaces in a variable name
- A space is NOT a letter, number or underscore character
Check Yourself
Which of the following are valid variable names?
var myHello2;
var 2myHello;
var My_HeLlO;
var my hello;
var a_very_long_variable_name_that_is_hard_to_read;
var hel-lo;
^ top
4.3.3: Assigning a Value to a Variable
^ top
4.3.4: Writing a Variable Value to a Web Document
Combining Text Strings
- JavaScript lets you combine a variable with a text string using the plus (
+) sign
- For example:
var libName = "Monroe Public Library";
document.write("<p>Welcome to the " + libName + "</p>)";
- JavaScript also lets you combine multiple text variables and strings using a plus (
+) sign
- For example:
var userName = "eparrish";
var emServer = "nowhere.com";
var emLink = userName + "@" + emServer;
document.write(emLink);
^ top
4.3.5: JavaScript Data Types
Why Does Strong and Weak Typing Matter?
- Why are some languages strongly typed and others weakly typed?
- Weakly-typed languages are convenient because they save you the trouble of deciding on and typing a data type
- However, this convenience can lead to unpredictable results if you are not careful
- For example, in JavaScript the plus symbol (+) has two purposes
- When used with two numbers, it adds them together
- For example:
var sum = 2 + 3;
document.write(sum);
- When used with a string, it combines two text strings into one string
- For example:
var fullName = "Ed " + "Parrish";
document.write(fullName);
- What happens if you combine a number and a string together?
- For instance:
var x = 5;
var y = "4";
var z = x + y;
document.write(z);
- The rule that JavaScript follows is that combining numbers and text always produces text
- What happens is not always readily apparent from reading the code
- In future lessons, we will look at how to manipulate text and numeric properties of variables
- For now, you just need to know about the different types
^ top
4.3.6: Summary
Check Yourself
- How do you store data in a program?
- What are the four data types supported by JavaScript?
- What code do you use to declare a variable named weekDay and assign it a value of "Friday"?
^ top
Activity 4.3
Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.
Quick Quiz
^ top
4.4: Creating Functions
Learner Outcomes
At the end of the lesson the student will be able to:
- Create and call a JavaScript function
- Return values from functions
|
^ top
4.4.1: About Functions
- Recall the case study from the textbook
- Using variables, we might use code like the following to display an email address:
var userName = "cadler";
var emServer = "mpl.gov";
var emLink = userName + "@" + emServer;
document.write("<a href='mailto" + emLink + "'>");
document.write(emLink);
document.write("</a>");
- This code displays one email address
- What would we need to do to display two email address?
- We would end up with code like this:
var userName = "cadler";
var emServer = "mpl.gov";
var emLink = userName + "@" + emServer;
document.write("<a href='mailto" + emLink + "'>");
document.write(emLink);
document.write("</a>");
// HTML code here
var userName = "mikeli";
var emServer = "mpl.gov";
var emLink = userName + "@" + emServer;
document.write("<a href='mailto" + emLink + "'>");
document.write(emLink);
document.write("</a>");
- Do you notice any similarities in the code for displaying the first and second email addresses?
- It would be nice if there was a way to display the email addresses without creating longs lists of duplicate code
- You can do this in JavaScript by using a function
^ top
4.4.2: Defining a Function
- A function is a collection of commands that perform an action or return a value
- Once you define a function, you can execute the commands by using the function's name
Function Syntax
- The syntax for defining a function is:
function functionName(parameters) {
JavaScript commands
}
- Where the functionName is a name that the programmer choses and parameters are values passed to the function
- As an example, we can define a function to display an email address like this:
function showEm(userName, emServer) {
var emLink = userName + "@" + emServer;
document.write("<a href='mailto:" + emLink + "'>");
document.write(emLink);
document.write("</a>");
}
- Notice the various parts of the function:
- The keyword
function starts the definition of every function
- Following this you define the function's name
- You follow the same rules making up a name for a function as you do for a variable
- After the name you must have a set of parentheses
- Inside the parenthesis you define parameters, if any
- A parameter is like a variable except it is declared inside the function parentheses
- Also, a parameter is assigned a value when you use the function
- Some functions need parameters and some do not
- You decide on the parameters when you define the function
- In our example, it made sense to define two parameters
- After the parenthesis, you define the block of code that you want to execute
- The block starts with an opening curly brace: {
- The block ends with a closing curly brace: }
- Between the curly braces, you list all the commands you want the function to execute
^ top
4.4.3: Calling a Function
Flow of Control for a Function Call
- To understand how your code works, you need to trace its flow
- JavaScript code starts executing at the top of a page and works its way downward
- As mentioned before, JavaScript does not execute the statements in a function right away
- Instead, you have to call the function
- When you call the function, the flow jumps to the function and starts executing its commands
- When the flow reaches the end of the function, the flow returns to where the function was called
- Then JavaScript continues with the next statement after the function call
- You can see this in the following diagram
Function Call and Return
^ top
4.4.4: Functions and Variable Scope
- As we have seen, the commands of a function run only when called
- This has an effect on the way variables within a function are treated
- Essentially: if a variable is created in a function then it can only be used inside the function
- Where a variable can be used is known as its scope
- In JavaScript, a variable's scope can be either local or global
- Local scope: variable declared within a JavaScript function
- Global scope: variable not declared within a function
Testing the Effects of Scope
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Testing JavaScript</title>
</head>
<body>
<h1>Testing JavaScript</h1>
<script type="text/javascript">
var text1 = "Hello World";
var text4 = "Good night world";
function callValue(){
var text2 = "Hello All";
document.write("<br />" + text1 + ", " + text2);
}
function showValue(){
var text3 = "Good night all!";
document.write("<br />" + text4 + ", " +text3);
}
callValue();
showValue();
//document.write("<br />" + text1 + ", " + text2);
//document.write("<br />" + text4 + ", " + text3);
</script>
</body>
</html>
|
^ top
4.4.5: Returning a Value from a Function
- Sometime you want a function to calculate a value and then return the value
- For a function to return a value it must include a
return statement
- The syntax for defining a function that returns a value is:
function functionName(parameters) {
JavaScript commands that perform the calculation
return theValue;
}
- Where the return statement is required and theValue is the value the function returns
- For example, if we wanted to calculate the area of a rectangle, we could write a function like:
function areaRectangle(length, width) {
var area = length * width;
return area;
}
- When we call the function, we need to save, or make use of, the value it returns
var rectLength = 4;
var rectWidth = 5;
var rectArea = areaRectangle(rectLength, rectWidth);
document.write("Area is: " + rectArea);
- If we do not save the returned value, it disappears
^ top
4.4.6: Summary
- In this section we introduced the concept of functions
- You use functions to reduce the amount of duplicate code in a program
- Functions are a collection of commands whose purpose is to perform an action or return a value
- Once you define a function, you can execute the commands by using the function's name
- The syntax for defining a function is:
function functionName(parameters) {
JavaScript commands
}
- When you define a function, JavaScript ignores the commands at first
- In order to run the commands, you must call the function
- The syntax of a function call:
functionName(parameterValues);
- Since the commands of a function run only when called, this has an effect on the way variables within a function are treated
- Essentially: if a variable is created in a function then it can only be used inside the function
- Sometime you want a function to calculate a value and then return the value
- For a function to return a value it must include a
return statement
- The syntax for defining a function that returns a value is:
function functionName(parameters) {
JavaScript commands that perform the calculation
return theValue;
}
Check Yourself
- What are the two purposes of a JavaScript function?
- What is the syntax for defining a function?
- How does a parameter differ from a variable?
- What is the syntax for calling a function?
- What are the two variable scopes in JavaScript?
- What scope does a variable have when it is declared inside a function?
- What keyword do you use to return a value from a function?
- When a value is returned from a function, what do you do with the value?
^ top
Activity 4.4
In this activity we write text to a web page using functions.
Specifications
- If you do not have the following files on you computer, then save them to a convent place like the Desktop:
- Complete the instructions in Figure 1-15, 1-16 and 1-17 (pages JVS 22-24) of your textbook.
- If you have difficulty, please ask a classmate or your instructor for help.
^ top
4.5: Working with JavaScript
Learner Outcomes
At the end of the lesson the student will be able to:
- Access functions from an external JavaScript file
- Document code with multi-line and single-line comments
- Make use of basic techniques for debugging JavaScript code
|
^ top
4.5.1: Accessing an External JavaScript File
^ top
4.5.2: Commenting JavaScript Code
When to Make Comments
- Comments should be used sparingly in your code
- Essentially, there are just three situations in which you should use comments
- Unusual or Obscure Code
- Function Comment Block
- File Comment Block
- We discuss each of these situations below
- I expect you to follow these comment guidelines in your homework
Unusual or Obscure Code
- You should include a comment whenever you do something unusual or obscure in your JavaScript code
- This will help whomever is reading your code to understand it
Function Comment Block
- To use a function, you need to know what it does and how to call it
- To explain what a function does, you write a multi-line (block) comment immediately before the function
- For instance, before the showEm() function, you could write a comment like:
1
2
3
4
5
6
7
8
9
10
11
12
|
/**
This function displays a mailto link for an email
address.
@param userName The email user name.
@param emServer The email server name.
*/
function showEm(userName, emServer) {
var emLink = userName + "@" + emServer;
document.write("<a href='mailto:" + emLink + "'>");
document.write(emLink);
document.write("</a>");
}
|
- The function comment block should start with:
/**
- The parameters descriptions are often placed on a separate line
- However, you can describe the parameters in the rest of the description if preferred
File Comment Block
More information
- JSDoc: JavaScript documentation tool.
^ top
4.5.3: Using Comments to Hide JavaScript Code
^ top
4.5.4: Debugging Your JavaScript Programs
- As you work with JavaScript, you will inevitably write code that does not work
- Making programming mistakes is a part of the learning process
- Even experienced programmers make mistakes
- Debugging is the process of finding and removing errors is your code
- To help us understand debugging, we can classify JavaScript errors into three categories:
- Load-time error: occurs when script is first loaded by the JavaScript interpreter
- Run-time error: occurs after script has been successfully loaded and is being executed
- Logical errors: free from syntax and structural mistakes, but result in incorrect results
- The first two types of errors can be reported by the browser
- However, each browser displays errors differently
Microsoft Internet Explorer Error Reporting
- To see the error in Internet Explorer, you first need to install the Script Debugger tool
- Once you do, you will see a window like the following pop-up whenever IE detects an error
Firefox, Mozilla and NetScape Error Reporting
- To see errors in Firefox, Mozilla or NetScape browsers, you open the JavaScript Console window
- The window will list all the errors the browser detects
- To see more details about an error, you simply click on its link
Common Mistakes
- Misspelling a variable name
- Mismatched parentheses or braces
- Mismatched quotes
- Missing quotes
- See textbook page 35 for more information
Logical Errors
- The following example from the textbook shows a logical error
- Logical errors are usually the hardest to detect
- The browser cannot detect them because there are no syntax errors
Debugging Techniques and Tips
- It may sound obvious, but the best way to debug is to not write bugs into your code:
- Check before compiling -- do not "write, run and pray"
- When you write a section of code, check it over for anything you might have missed
- Work through it by hand if you are not sure it will work
- By preventing problems, you will spend much less time fixing bugs
- Write readable code:
- Use meaningful and descriptive variable and function names
- Use indentations and format your code consistently
- When code is formatted correctly, you can spot errors more easily
- Test your code often:
- Do not use "big-bang programming"
- Write a small section of code and verify it works before writing more
- Write modular code
- Break up a program's different tasks into smaller, more manageable chunks
- Use Alert Dialogs to report on program status and variables
- Dialog box generated by JavaScript that displays a text message with an OK button
- For example:
alert("OK to here");
- Another example:
alert(emLink);
- See textbook page 35 for more information
^ top
4.5.5: Summary
Tips for Writing Good JavaScript Code
- Apply layout techniques to make code more readable
- Use descriptive variable names
- Be consistent in how you apply uppercase and lowercase letters to your variable names
- Add comments to your code
- Create customized functions
- Break up long and complicated functions into smaller functions
- Use the debugging tools available in the browser
- In case of a logical error, use alert boxes
Check Yourself
- What code would you write to display the multi-line comment:
This function displays the current date in the format month, day, year.
- What are the three kinds of JavaScript errors?
- How can prevent bugs in your code?
- What command would you run to display the value of the
userName variable in an alert box?
- In your code you misspelled a variable name. What type of error will result from this mistake?
^ top
Activity 4.5
Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.
Quick Quiz
^ top
Wrap Up
Due Next: A4: Using JavaScript (10/2/06)
Discussion 3 and Quiz 3 (10/2/06)
^ top
Home
| WebCT
| Announcements
| Schedule
| Room Policies
| Course Info
Help
| FAQ's
| HowTo's
| Links
Last Updated: March 16 2007 @15:59:20
|