Java Script
Java Script
What is JavaScript?
CIS 233
Why Use JavaScript?
• Form validation
CIS 233
JavaScript Versus Java
CIS 233
JavaScript Versus Java
CIS 233
JavaScript Versus Java
CIS 233
JavaScript Syntax.
CIS 233
JavaScript Terminology.
CIS 233
Objects
CIS 233
Properties
CIS 233
Methods
CIS 233
Events
CIS 233
Functions
CIS 233
Values
CIS 233
Variables
CIS 233
Data Types
• Primitive data types
• Number: integer & floating-point numbers
• Boolean: true or false
• String: a sequence of alphanumeric characters
CIS 233
var obj = new Object(); // Creating an object
alert(keys);
// Show "prop1 prop2 pro3 "
alert(values);
// Show "123 456 true "
CIS 233
// An array of 3 elements, each element is undefined
var tmp1 = new Array(3);
CIS 233
Null & Undefined
CIS 233
Type Conversion (To Boolean)
CIS 233
Type Conversion
CIS 233
Expressions
CIS 233
Operators
CIS 233
Methods of Using JavaScript.
CIS 233
1. Using Separate JavaScript Files.
<script src="myjavascript.js”
language="JavaScript1.2”
type="text/javascript">
</script>
CIS 233
2. Embedding JavaScript in HTML.
<script language="javascript”
type="text/javascript">
<!-- Begin hiding
window.location=”index.html"
// End hiding script-->
</script>
CIS 233
Using Comment Tags
CIS 233
3. Using JavaScript in HTML Tags.
<a href=”index.html”
onMouseover="document.logo.src='js2.gif'"
onMouseout="document.logo.src='js.gif'">
<img src="js.gif" name="logo">
</a>
CIS 233
Creating an Alert Message
CIS 233
Conditional Statements
• “if” statement
• “switch” statement
• The syntax of these statements are similar to those
found in C and Java.
CIS 233
Looping Statement
• “for” Loops
• “for/in” Loops
• “while” Loops
• “break” statement
• “continue” statement
• All except "for/in" loop statements have the same syntax as those
found in C and Java.
CIS 233
“for/in” statement
for (var variable in object) {
statements;
}
CIS 233
var keys = "", values = "";
var mylist = new Array("Chinese", "English", "Jap");
mylist.newField1 = "Something";
CIS 233
Functions
• Abstraction
• Experience has taught us that much code is duplicated
throughout program
• Functions let us write the functionality once, then reuse it
• Encapsulation
• Functions encapsulate a specific capability or
feature
• Function name allows us to access a function in our
program
CIS 233
Function
• Parameterization
• We can customize the function’s result by
passing in different values each time we use it
CIS 233
Function Used
CIS 233
Function Issues
CIS 233
JavaScript Functions – Naming
• Function names
• Name describes what function does
• Name is an identifier, so follow JS identifier
syntax rules & course coding standards
• Example
findMaxValue(‘put some parameters here’)
CIS 233
JavaScript Functions -- Parameters
• Passing parameters to the function
• Parameters provide functions with input
• Implicitly declared variables that can be accessed by
code within function body
• You provide actual input values when you call the
function
• Parameters are named variables separated by commas
• Example,
function findMaxValue(num1, num2, num3)
CIS 233
JavaScript Functions – Where to put?
• Put functions within <script>….</script> tags within the
<head> section of the web page
<head>
<script language=“JavaScript”>
</script>
</head>
CIS 233
JavaScript Functions – Local Variables
• If needed, you can declare local variables within a
function
CIS 233
JavaScript Functions – Local
Variables
function findMaxValue(num1, num2,num3) {
var tempMax; //local var
else {
tempMax = num2;
}
return tempMax;
} //end function
CIS 233
JavaScript Functions -- Calling
• To call a function from your program, add a statement
that contains the function name with values for the
parameters the function requires
var x = 1, y = 4, z = 2;
findMaxValue(x, y, z);
CIS 233
JavaScript Functions -- Return
• Return keyword tells function to return some
value and exit immediately
CIS 233
JavaScript Functions -- Return
• Good Example
• Uses var maxNumber in calling program
• Function’s return value is assigned to maxNumber
• Display of maxNumber has correct value for inputs
• Code snippet
var x = 1, y = 4, z = 2;
var maxNumber = findMaxNumber(x, y, z);
document.write(“The maximum is: “ + maxNumber);
CIS 233
JavaScript Functions -- Return
• The return must be handled properly or it will be ‘lost’
• Bad Example1,
• Declares var maxNumber in calling program, then
displays it
• Value is ‘undefined’ because maxNumber is never
initialized & the return value is never assigned to it
CIS 233
JavaScript Functions -- Return
• Bad Example 2
• Declares var tempMax in calling program
because that’s the name of the var being
returned from function
• Attempts to display tempMax but value is
undefined
• the tempMax in calling program may have the
same name as var being ‘returned’ but they are
different variables!
CIS 233
JavaScript Functions – Parameter
Sequence
• When calling functions, must enter parameters in same order as
specified in function argument list.
4. return density;
5. }
6. ……………………………………………….
CIS 233
JavaScript Functions – Global
Variables
• Global variables are those declared outside of
functions
function writeHello() {
document.write(globalHello);
// outputs “Hello!”
CIS 233
JavaScript Functions – Testing
CIS 233
JavaScript Functions – Debugging
CIS 233
JavaScript Functions
• Built-In Functions
• Prompt
• Alert
• Confirm
CIS 233
alert(), confirm(), and prompt()
<script type="text/javascript">
alert("This is an Alert method");
confirm("Are you OK?");
prompt("What is your name?");
prompt("How old are you?","20");
</script>
CIS 233
JavaScript and HTML Forms
CIS 233
JavaScript and HTML Forms
history [length]
CIS 233
JavaScript and HTML Forms
CIS 233
JavaScript and HTML Forms
• Methods
• Behavior associated with an object
• Essentially functions that perform an action
• Some are built in and others user made
CIS 233
JavaScript and HTML Forms
• User Events
• An event occurs when a user makes a change to a
form element
Ex. Click a button, mouseover an image
• Detection of an event done by event handlers
• Event handler is an attribute of the HTML button
• <form>
<input type=button value=“please click”
onclick=“function name()”>
• </form>
CIS 233
JavaScript and HTML Forms
<HTML>
<HEAD>
<SCRIPT LANGUAGE=JavaScript><!--
function changecolor(){
document.bgColor="#ff0000";
//--></SCRIPT>
</HEAD>
<BODY>
<P><FORM >
</FORM>
</BODY>
</HTML>
CIS 233
JavaScript and HTML Forms
• Form Object
• Window.document.form
• A form is a property of the document but is also an
object
• Form elements are properties of a form and are also
objects
• Access to form’s properties is done through the
NAME attribute of the FORM tag
• Access to the properties of the form elements is
done through the NAME attributes of the particular
form element
CIS 233
JavaScript and HTML Forms
<HEAD>
<SCRIPT LANGUAGE=JavaScript><!--
function plus(){
n1=parseFloat(n1);
<P><FORM name=addmult>
n2=parseFloat(n2);
<P>Enter a number in each field:
n1=parseFloat(n1);
<INPUT TYPE=reset VALUE="Reset Form"><BR>
n2=parseFloat(n2);
<TEXTAREA NAME=result ROWS=3 COLS=27
document.addmult.result.value=n1*n2; WRAP=virtual></TEXTAREA>
}
</FORM>
</BODY>
</HTML>
CIS 233
JavaScript and HTML Forms
Form for submitting info for server side
processing
• <HTML> • <TR>
• <TD WIDTH=83>
• <HEAD>
• <P>Address:
• <SCRIPT LANGUAGE=JavaScript><!-- • </TD>
• else { • </TD>
• <TD>
• display.value="The following information has been added to our
guestbook:\r"+fullname.value+"\r"+ address.value +"\r" +email.value; • <P><INPUT TYPE=text NAME=email VALUE="" SIZE=32>
• } • </TD>
• </TR>
• }
• <TR>
• } • <TD WIDTH=83>
• </TD>
• </HEAD>
• <TD>
• <BODY BGCOLOR="#FFFFCC">
• <P><INPUT TYPE=reset VALUE="Clear Your Information">
• <P><FORM name=infoform> • </TD>
• <TR>
• <TR>
• <TD COLSPAN=2>
• <TD WIDTH=83> • <P><TEXTAREA NAME=display ROWS=5 COLS=41 WRAP=virtual></TEXTAREA>
• <P>Name: • </TD>
• </TR>
• </TD>
• </TABLE>
• <TD>
• </TD> • </BODY>
• </HTML>
• </TR>
CIS 233
Event Handlers
CIS 233
onMouseOver & onMouseOut
Event Handler
<html>
<head>
<title>onMouseOver / onMouseOut Event Handler Demo</title>
</head>
<body>
<a href="http://www.cuhk.edu.hk"
onMouseOver="window.status='CUHK Home'; return true;"
onMouseOut="status=''"
>CUHK</a>
</body>
</html>
• When the mouse cursor is over the link, the browser displays the text "CUHK
Home" instead of the URL.
• The "return true;" of onMouseOver forces browser not to display the URL.
• window.status and window.defaultStatus are disabled in Firefox.
CIS 233
onSubmit Event Handler
<html><head>
<title>onSubmit Event Handler Example</title>
<script type="text/javascript">
function validate() {
// If everything is ok, return true
// Otherwise return false
}
</script>
</head>
<body>
<form action="MessageBoard" method="POST"
onSubmit="return validate();"
>
…
</form></body></html>
• See online references for complete list of available methods in these objects:
http://javascript-reference.info/
CIS 233
String Object (Some useful methods)
• length
•A string property that tells the number of character in the string
• charAt(idx)
•Returns the character at location "idx"
• toUpperCase(), toLowerCase()
•Returns the same string with all uppercase/lowercase letters
• substring(beginIdx)
•Returns a substring started at location "beginIdx"
• substring(beginIdx, endIdx)
•Returns a substring started at "beginIdx" until "endIdx" (but not including
"endIdx"
• indexOf(str)
•Returns the position where "str" first occurs in the string
CIS 233
Error and Exception Handling in
JavaScript
• Javascript makes no distinction between Error and
Exception (Unlike Java)
• Handling Exceptions
• The onError event handler
A method associated with the window object.
It is called whenever an exception occurs
} catch ( errorVariable ) {
// Codes here get executed if an exception is thrown
// in the try block.
} finally {
// Executed after the catch or try block finish
} catch( errVar ) {
document.write("Exception caught<br>");
// errVar is an Error object
// All Error objects have a name and message properties
document.write("Error name: " + errVar.name + "<br>");
document.write("Error message: " + errVar.message +
"<br>");
} finally {
document.write("Finally block reached!");
}
</script>
CIS 233
Throwing Exception
<script type="text/javascript">
try{
var num = prompt("Enter a number (1-2):", "1");
// You can throw exception of any type
if (num == "1")
throw "Some Error Message";
else
if (num == "2")
throw 123;
else
throw new Error ("Invalid input");
} catch( err ) {
alert(typeof(errMsg) + "\n" + err);
// instanceof operator checks if err is an Error object
if (err instanceof Error)
alert("Error Message: " + err.message);
}
</script> CIS 233
• Return to jqjacobs.net/web -- JavaScript Basics
JavaScript for the World Wide Web by Tom Negrino and Dori Smith
CIS 233