Introduction to javascript
1 / 113

Introduction to JavaScript - PowerPoint PPT Presentation

  • Updated On :

Introduction to JavaScript. From the InfoTech Internet/Intranet Series. Presented by Dr. Billy Lim Developed by Dr. Billy B. L. Lim & Dr. Joaquin Vila Applied Computer Science Illinois State University. Agenda. Introduction Basic Language Features

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

PowerPoint Slideshow about 'Introduction to JavaScript' - reuben

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Introduction to javascript

Introduction to JavaScript

From the InfoTech Internet/Intranet Series

Presented by

Dr. Billy Lim

Developed by

Dr. Billy B. L. Lim & Dr. Joaquin Vila

Applied Computer Science

Illinois State University


  • Introduction

  • Basic Language Features

    • variables, expressions, operators, statements

  • The JavaScript Object Model

    • objects, properties, methods, events

  • Built-in Objects and Functions

  • Examples and Miscellany

What is javascript
What is JavaScript?

  • (Formerly LiveScript) Sun's simple, cross-platform, WWW scripting language adopted by Netscape and allies.

  • Compact, user-level, object-based  now OO

  • Ideal for making web pages “smart”

  • Brief history

    • developed (late 1995) primarily by Netscape, but in cooperation with Sun Microsystems

      • Brendan Eich (Netscape)

      • Bill Joy (Sun Microsystems)

Why javascript
Why JavaScript?

  • Java and JavaScript becoming defacto standards

  • Huge leap from static HTML coding to Java programming

  • Scripting makes things easy

  • No additional tools needed

    • (a browser and text editor will do!)

Server based processing
Server Based Processing


Client (browser)



User’s Input

Client based processing
Client Based Processing


Client (browser)

User’s Input





Uses of javascript
Uses of JavaScript

  • Tailor pages for the user

  • Make interactive pages

  • Process forms

  • Provide CAI (computer-aided instructions)

  • Special effects

Javascript and navigator and ie versions
JavaScript and Navigator (and IE) versions

Navigator versionDefault JavaScript version<SCRIPT> tags supported

Navigator earlier than 2.0 JavaScript not supported None

Navigator 2.0, I.E., 3.0a JavaScript 1.0 <SCRIPT LANGUAGE="JavaScript">

Navigator 3.0, IE 3.0b JavaScript 1.1 <SCRIPT LANGUAGE = "JavaScript1.1">

and all earlier versions

Navigator 4.0-4.05, IE 4.0 JavaScript 1.2 <SCRIPT LANGUAGE = "JavaScript1.2">

and all earlier versions

Navigator 4.06-4.7, IE 5.0 JavaScript 1.3 <SCRIPT LANGUAGE = "JavaScript1.3">

and all earlier versions

IE 5.0 (partially) JavaScript 1.4 <SCRIPT LANGUAGE = "JavaScript1.4">

and all earlier versions

Navigator 6, IE 5.5-6.0 JavaScript 1.5 <SCRIPT LANGUAGE = "JavaScript1.5">

and all earlier versions

Note: Microsoft’s version is called JScript

Official standard is called ECMAScript

Using javascript in html
Using JavaScript in HTML

  • JavaScript can be embedded in a HTML document in three ways:

    • 1. As statements and functions using the SCRIPT tag.

    • 2. As event handlers using HTML tags.

    • 3. In javascript: <some javascript code here>

Your first javascript program
Your First JavaScript Program

FileName: hello.htm




// This is a comment in JavaScript

document.write("<h1>Hello folks!</h1>");




Welcome to this class!




<script type="text/javascript">

First program cont d
First Program (cont’d)

  • <SCRIPT> and </SCRIPT> tags must surround your JavaScript code

    <SCRIPT LANGUAGE="JavaScript">

    document.write("<h1>Hello folks!</h1>");


  • Safest to put the tags within the <HEAD>

  • LANGUAGE attribute is optional

Write method
write Method

  • document.write directs the document object to write the given string

  • Examples:


    counter = 10;


    document.write("<h1>Counter is "+counter+"</h1>");



    document.write("<IMG SRC=‘small.gif’>"); // notice the use of “ and ‘


Concatenate the strings and number

together and write the resulting

string out

Simple interactions
Simple Interactions

  • alert

    • Displays an Alert dialog box with a message and an OK button.

    • Syntax: alert("message");

    • Example: alert(“You’re in a Special Area …”);

      alert(“count=“+count); // count is a variable to be traced here

  • confirm

    • Displays a Confirm dialog box with the specified message and OK and Cancel buttons.

    • Syntax: confirm("message");

    • Example: ans = confirm(“Are you sure you want to continue?”);

      • ans will be true if OK is clicked or false if Cancel is clicked

Simple interactions 2
Simple Interactions (2)

  • eval

    • The eval function evaluates a string and returns a value.

    • Syntax: eval(stringExpression)

    • Example: eval(1+2*3) // gives 7 here

  • prompt

    • The prompt function prompts for a string value.

    • Syntax: prompt(“message”) or prompt(“message”, default value)

    • Example:

      • aString1 = prompt(“Enter Name”);

      • aString2 = prompt(“Enter Salary”, 0);

        • Note: The return value is a string. Need to convert if a numeric value is desired. Use parseInt() or parseFloat().

        • Example: numSalary = parseInt(aString2); // parse aString2 into an int

          numSalary = numSalary + 500;

Using javascript on the location field
Using javascript: (on the location field)

  • Can test the simple interactions discussed above with the command to invoke the JavaScript interpreter – javascript: on the location field of your browser (see figure below).

Javascript debugging
JavaScript Debugging

  • In Firefox, Netscape, and Mozilla, type javascript: (on the location field) to get the console window so that you can see the error messages generated. Also, go to Error Console under Tools menu.

Javascript debugging 2
JavaScript Debugging (2)

  • In Chrome, go to Tools > Developer Tools. The window should display the error, as shown below

Javascript debugging 3
JavaScript Debugging (3)

  • In IE, when there is a script error on a page, a message appears on the bottom left corner. Double click on it to see the error.

Javascript debugging 4
JavaScript Debugging (4)

  • Firebug extension for Firefox (

Javascript vs c c
JavaScript vs. C/C++

  • Similarities (apply to Java too)

    • comments /* */ and //

    • if, for, while, return

    • operators (arithmetic, relational, etc.)

  • Differences

    • In JavaScript

      • loose typing

      • no file I/O library

      • no pointers

      • built-in string object

Data types
Data Types

  • Numbers

    • 1, 3.14159, -99

  • Logical (Boolean) values

    • true or false (these two are the literal values that you use to test the truth value of a logical expression)

  • Strings

    • “hello”, ‘hello’

  • null

    • special keyword denoting null value

String literals
String Literals

  • A string literal is zero or more characters enclosed in double (") or single (') quotes. A string must be delimited by quotes of the same type; that is, either both single quotes or double quotes. The following are examples of string literals:

    • "Hello"

    • 'Hello'

    • "1234"

    • “one line \n another line”

    • '"Don\'t try that again!," I yelled.'

Escape character for single quote


  • You use variables to hold values in your application.

    • Syntax:

      varVariablename ; // var => local variable; Otherwise, the variable is global

      var Variablename = value;

  • JavaScript is a loosely typed language.

    myVar = 33;

    myVar = “Hello World”;

    myVar = 33 + “Hello World”; // gets “33Hello World”

    myVar = “Hello World” + 33; // gets “Hello World33 ”

Variable names
Variable Names

  • A JavaScript identifier or name must start with a letter or underscore ("_"); subsequent characters can also be digits (0-9). Letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase). JavaScript is case-sensitive.

  • Some examples of legal names are:

    • Last_Name

    • status

    • _name


  • Arithmetic

    + (Addition, String Concatenation)

    - (Subtraction, Unary Negation)

    * (Multiplication)

    / (Division)

    % (Modulus) (e.g., 7 % 3 gives 1, the remainder of dividing 7 by 3)

    ++ (Preincrement, Postincrement) // increments a variable by 1

    e.g., x = 1; alert(x++); alert (x) // displays 1, then 2

    e.g., x = 1; alert(++x); alert (x) // displays 2, then 2

    -- (Predecrement, Postdecrement) // decrements a variable by 1

    e.g., x = 1; alert(x--); alert (x) // displays 1, then 0

    e.g., x = 1; alert(--x); alert (x) // displays 0, then 0

Operators cont
Operators (Cont...)

  • Assignment Operators

    = means assignment

    PI = 3.14159; // var PI is assigned 3.14159

    Op= (where op is one of +, -, *, /, etc.)

    x += y means x = x + y

    x *= y means x = x * y

    x -= y means x = x - y

    x /= y means x = x / y

Operators cont1
Operators (Cont...)

  • Relational Operators

    ==, != (Equality, Inequality)

    <, <=, =>, > (Arithmetic and String Comparison)

    ! (Logical Not)

    &&, || (Logical AND, Logical OR)

    ?: (Conditional Selection)

    e.g., x = (1 < 5) ? ‘a’:’b’; // here, x gets ‘a’


Returned if true

Returned if false

Operator precedence
Operator Precedence

  • The precedence of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses.

  • The precedence of operators, from lowest to highest is as follows: (Partial Listing)

    • assignment = += -= *= /= %=

    • conditional ?:

    • logical-or ||

    • logical-and &&

    • equality == !=

    • relational < <= > >=

    • addition/subtraction + -

    • multiply/divide * / %

    • negation/increment ! ++ --

    • call, member () [] .


  • An expression is any valid set of literals, variables, and operators that evaluates to a single value.

    PI = 3.14159

    12 + 6

    2 * PI * r


    x -= 3


  • Comments

  • Variable Declaration / Assignment

  • Conditionals

  • Loops

    • for loop

    • while loop

    • loop

    • break and continue statements

  • with statement

  • Function Definition


  • // Single Line

  • var x // this part of the line is a comment

  • /* Multiline Comment

    Line 2.....

    Line 3 */



if (condition) {


} [else { else statements


Note: else part is not required; [ ] signifies that it is optional



var marriedCount = 0;

var singleCount = 0;

status = prompt("What is your status (0 or 1)?")

if (status == 1) {

deduction = 500;


} else {

deduction = 100;



alert("Your deduction is: " + deduction);



Loops for
Loops – for

  • Syntax

    for ([initial expression]; [condition]; [update expression]) {



  • Example

    for (var i = 0; i < 10; i++) {





Loops for in
Loops – for-in

  • Syntax

    for (varin obj) {



  • Examples

    FileName: Winloop.htm


    // The following script shows all of the properties of the window object.

    for (var i in window)

    document.write (i + "<BR>");


    FileName: Winloop2.htm


    // The following script shows all of the properties and their values of the window object.

    for (var i in window)

    document.write (i + "=" + window[i]+ "<BR>");


Loops while
Loops – while

  • Syntax

    while (condition) {



  • Example

    n = 0;

    x = 0;

    while ( n < 3 ) {

    n ++ ;

    x = x + n;



  • Output:

  • 1

  • 3

  • 3 6


  • Function

    • A user-defined or built-in set of statements that perform a task. It can also return a value when used with the return statement.

    • Syntax:

      function name([param] [, param] [..., param]) { // param’s are optional



  • Example

    // Takes 2 values and returns the smaller of the two

    function findMin (value1, value2) {

    if (value1 < value2)

    return (value1);


    return (value2);


    answer = findMin(50,50); // function call

    alert("Your answer is: " + answer);



Arguments and parameters
Arguments and Parameters

FileName: argument.htm



<!-- to hide script contents from old browsers

function square(i) {

document.write("The call passed “+ i + " to the function.“+"<BR>")

return i * i


document.write("The function returned “+square(8)+".")

// end hiding contents from old browsers -->





All done.



  • An array is an ordered set of values associated with a single variable name.

    • Syntax:

      arrayName = new Array()

      arrayName = new Array(arrayLength) // no enforcement of length

    • To access the elements of an array


    • The first element of an array has an index of zero (0)

Arrays cont
Arrays (Cont...)

  • Example: Each of these elements can be accessed by its index, as follows:

    • myCar[0] = "Ford"

    • myCar[1] = "Mustang"

    • myCar[2] = 67

  • Note:

    • Array elements can be heterogeneous (can contain elements of multiple data types)

Arrays cont1
Arrays (Cont...)

  • Properties and arrays in JavaScript are intimately related; in fact, they are different interfaces to the same data structure.

  • Example:

    • you could set the properties of the myCar object described above as follows:

      • myCar["make"] = “Benz"

      • myCar["model"] = “M Class 320"

      • myCar["year"] = 99


      • myCar.make = " Benz"

      • myCar.model = " M Class 320"

      • myCar.year = 99

Arrays cont2
Arrays (Cont...)

  • Example:

    FileName: Array-with-ForIn.htm

    // This prints only the defined values of the array


    for (i in anArray)

    document.write("anArray at "+i+" = "+anArray[i] +"<BR>");


Arrays cont3
Arrays (Cont...)

  • Other syntax of defining arrays: // TestOtherArraySyntax.htm


    function compare(a,b) {

    return a-b;


    anArray = new Array("Freshman","Sophomore","Junior","Senior");

    anArray2 = ["Computer Science","Mathematics","Accounting","Biology","Political Science"];

    anArray3 = [10, 300, 20, 40];

    for (i in anArray)

    document.write("anArray at "+i+" = "+anArray[i] +"<BR>");


    anArray2.sort(); // do sorting of strings

    for (i in anArray2)

    document.write("anArray at "+i+" = "+anArray2[i] +"<BR>");


    anArray3.sort(); // does not sort the numbers!

    for (i in anArray3)

    document.write("anArray at "+i+" = "+anArray3[i] +"<BR>");



    for (i in anArray3)

    document.write("anArray at "+i+" = "+anArray3[i] +"<BR>");


Arrays cont4
Arrays (Cont...)

  • JavaScript’s Object Model (later on this) consists of many arrays that allow you to manipulate the objects on a web document.

  • For example,

    • frames (from window) // window.frames[0]….

    • anchors (from document) // document.anchors[0]….

    • applets (from document) // document.applets[0]….

    • forms (from document) // document.forms[0]….

    • images (from document) // document.images[0]….

    • layers (from document) // document.layers[0]….

    • links (from document) // document.links[0]….

    • elements (from form) // document.forms[0].elements[0]….

    • options (from select) // document.forms[0]. elements[0].options[0]….

Javascript object model
JavaScript Object Model

  • Object-based (not object-oriented) scripting language

    • can manipulate instances of JavaScript’s built-in object types

      • e.g., date, document, location, etc.

    • objects have properties (i.e., characteristics of objects)

      • e.g., document.bgColor, ...

    • objects have methods (i.e., services provided by the objects)

      • e.g., document.write(“Hello”), ...

  • Can also create and use your own objects

    • later on this ...

Objects and properties
Objects and Properties

  • Objects in Navigator exist in a hierarchy that reflects the hierarchical structure of the HTML page itself

HTML Page in a Window

Corresponding JavaScript Objects

window (= the window instance)

document (= the page)

links (= array with all the links

in the page)

images (= array with all the images)


Introduction to javascript












Objects and properties 2



Property of parent object

an object and

a property



Property of child object

Property only

Objects and Properties (2)

  • An object's "descendants" are properties of the object

    • e.g., a form named "form1" is an object, but is also a property of document, and is referred to as "document.form1"

Object hierarchy dom
Object Hierarchy (DOM)

  • Built-in Objects:

  • String

  • • Date

  • • Array

  • • Boolean

  • • Math

Objects in a page
Objects in a Page

  • Every page has the following objects:

    • navigator: has properties for the name and version of the Navigator being used, for the MIME types supported by the client, and for the plug-ins installed on the client.

    • window: the top-level object; has properties that apply to the entire window. There is also a window object for each "child window" in a frames document.

    • document: contains properties based on the content of the document, such as title, background color, links, and forms.

    • location: has properties based on the current URL.

    • history: contains properties representing URLs the client has previously requested.

  • Depending on its content, the document may contain other objects.

    • For instance, each form (defined by a FORM tag) in the document has a corresponding Form object.

Objects at work
Objects at Work

FileName: firstFormEvent.htm



function compute(aForm) {

if (confirm("Are you sure?"))

aForm.result.value = eval(aForm.expr.value)


alert("Please come back again.")



<FORM name=“MyForm”>

Enter an expression:

<INPUT TYPE="text" NAME="expr" SIZE=15 >

<INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)“ >



<INPUT TYPE="text" NAME="result" SIZE=15 >


Objects at work1
Objects at Work

  • Dissection of the example

    • “this” refers to the object in question

    • this.form refers the form that the object in question is defined in

      • Thus, “compute(this.form)” calls the compute function and passes the form that the button object resides in to the function.

      • Other means of passing:

        • “compute()” => Here, no form is passed into the function. Thus, to access result, one needs document.MyForm.result.value instead of form.result.value (the same is true for expr)

        • “compute(this)” => Here, the button object is passes into the function. This would not be meaningful since the button object itself in not needed in the function. The two text fields are the ones that are needed.

Document object use getelementbyid
Document Object: UsegetElementById()



<script type="text/javascript">

function getElement() {

var x=document.getElementById("myHeader")

alert("I am a " + x.tagName + " element")


function getElement2() {

var x=document.getElementsByName("myHeader2") // x gets an array of elements

alert("I am a " + x[0].tagName + " element")





<h1 id="myHeader" onclick="getElement()">Click to see what element I am!</h1>

<h2 name="myHeader2" onclick="getElement2()">Click to see what element I am!</h1>



Source: Modified from Shin’s JavaScript

Document object use getelementsbyname
Document Object: UsegetElementsByName()



<script type="text/javascript">

function getElements() {

var x=document.getElementsByName("myInput")

alert(x.length + " elements!")





<input name="myInput" type="text" size="20"><br />

<input name="myInput" type="text" size="20"><br />

<input name="myInput" type="text" size="20"><br />

<br />

<input type="button" onclick="getElements()" value="How many elements named 'myInput'?">



Source: Shin’s JavaScript

Featured objects

Featured Objects

(in alphabetical order)

Checkbox object
Checkbox Object

  • A checkbox on an HTML form

  • A toggle switch that lets the user set a value on or off

  • Properties

    • checked lets you programatically check a checkbox

    • defaultChecked reflects the CHECKED attribute

    • name reflects the NAME attribute

    • value reflects the VALUE attribute

Checkbox object 2
Checkbox Object (2)

  • Methods: click

  • Event handlers: onClick

  • Property of: form

  • Example:

    The following example displays a group of four checkboxes that all appear checked by default.

    • <B>Specify your music preferences (check all that apply):</B>

    • <BR><INPUT TYPE="checkbox" NAME="musicpref_rnb" CHECKED> R&B

    • <BR><INPUT TYPE="checkbox" NAME="musicpref_jazz" CHECKED> Jazz

    • <BR><INPUT TYPE="checkbox" NAME="musicpref_blues" CHECKED> Blues

    • <BR><INPUT TYPE="checkbox" NAME="musicpref_newage" CHECKED> New Age

Checkbox object 3
Checkbox Object (3)

  • Example:

    FileName: toUpper.htm


    function convertField(field) {

    if (document.form1.convertUpper.checked) {

    field.value = field.value.toUpperCase()}


    function convertAllFields() {

    document.form1.lastName.value = document.form1.lastName.value.toUpperCase()

    document.form1.firstName.value = document.form1.firstName.value.toUpperCase()



    <FORM NAME="form1">

    <B>Last name:</B>

    <INPUT TYPE="text" NAME="lastName" SIZE=20 onChange="convertField(this)">

    <BR><B>First name:</B>

    <INPUT TYPE="text" NAME="firstName" SIZE=20 onChange="convertField(this)">

    <P><INPUT TYPE="checkBox" NAME="convertUpper"

    onClick="if (this.checked) {convertAllFields()}"> Convert fields to upper case


Date object
Date Object

  • Gets and sets the dates and times.

  • A top-level built-in object

  • Two (of many) ways to create a Date object:

    • dateObjectName = new Date() // current moment

    • dateObjectName = new Date(year, month, day, hours, minutes, seconds)

  • Properties

    • None.

Date object 2
Date Object (2)

  • Methods (partial list)

    • getDate, getDay, getHours, getMinutes, getMonth, getSeconds, getTime, getYear, parse, setDate, setHours, setMinutes, setMonth, setSeconds, setTime, setYear, toGMTString, toLocaleString, UTC

  • Event handlers

    • None. Built-in objects do not have event handlers.

  • Property of

    • None.

Date object 3
Date Object (3)

  • Examples

    • now = new Date()

    • birthday = new Date("December 17, 1995


    • birthday = new Date(95,11,17) // month’s range: 0 - 11

    • birthday = new Date(95,11,17,3,24,0)

    • currentYear = birthday.getYear()

Date object 4
Date Object (4)

  • Examples


    now = new Date();

    document.write("Time: "+now.getHours()+":"+now.getMinutes()+"<br>");

    document.write("Date: ” + (now.getMonth()+1) + "/” + now.getDate() + "/” + (1900+now.getYear()));



    Time: 9:48

    Date: 6/16/1999

  • Better to use getFullYear()

    • This gives a 4-digit year

Need this addition in Netscape.

IE will return the correct year

Document object
Document Object

  • Contains information on the current document (e.g., title, last modified, color), and provides methods for displaying HTML output to the user.

  • To use a document object's properties and methods:

    • 1. document.propertyName

    • 2. document.methodName(parameters)

Document object 2
Document Object (2)

  • Properties

    • alinkColor reflects the ALINK attribute

    • anchors is an array reflecting all the anchors in a document

    • applets is an array of objects corresponding to the applets in a document in source order.

    • bgColor reflects the BGCOLOR attribute

    • cookie specifies a cookie (string value representing all of the cookies associated with this document)

    • fgColor reflects the TEXT attribute

    • forms is an array reflecting all the forms in a document

    • lastModified reflects the date a document was last modified

    • linkColor reflects the LINK attribute

    • links is an array reflecting all the links in a document

    • location reflects the complete URL of a document

    • referrer reflects the URL of the calling document

    • title reflects the contents of the <TITLE> tag

    • vlinkColor reflects the VLINK attribute

Document object 3
Document Object (3)

  • Methods

    • clear, close, open, write, writeln

  • Event handlers

    • None. The onLoad and onUnload event handlers are specified in the <BODY> tag but are actually event handlers for the window object.

  • Property of

    • Window (or Frame) object

  • Examples:

    • document.fgColor = "#ff0000"

    • document.form1.controlname = ...

Form object forms array
Form Object (Forms Array)

  • Lets users input text and make choices from form objects such as checkboxes, radio buttons, and selection lists.

  • Can also be used to post data to a server

  • To use a form object's properties and methods:

    • 1. formName.propertyName

    • 2. formName.methodName(parameters)

    • 3. forms[index].propertyName

    • 4. forms[index].methodName(parameters)

Form object forms array 2
Form Object (Forms Array) (2)

  • The forms array

    • 2 ways of referencing forms

      • by using the forms array

      • by using the form names

    • form array contains an entry for each form object (<FORM> tag) in a document in source order.

    • e.g., if a document contains three forms, these forms are reflected as document.forms[0], document.forms[1], and document.forms[2].

    • To use the forms array:

      • 1. document.forms[index]

      • 2. document.forms.length

Form object forms array 3
Form Object (Forms Array) (3)

  • Properties

    • action reflects the ACTION attribute

    • elements is an array reflecting all the elements in a form

    • encoding reflects the ENCTYPE attribute

    • length reflects the number of elements on a form

    • method reflects the METHOD attribute

    • target reflects the TARGET attribute

    • length reflects the number of forms in a document (for forms array)

  • Methods: submit

  • Event handlers: onSubmit

  • Property of: document

Frame object frames array
Frame Object (Frames Array)

  • Frames enable the display of multiple independently scrollable frames on a single screen, each with its own distinct URL.

  • Frames can point to different URLs as well as be targeted by other URLs - all within the same screen.

Frames 2
Frames (2)

  • Frames HTML Syntax:







    The Frame definitions go between the frameset tags

Frames 3
Frames (3)

  • The arguments taken by frameset tag are

    • ROWS - is the row values for the frames embedded in that frameset.

    • COLS - takes the column values for the frames in the frameset

    • the values can be numbers or percentages

  • Example

    <frameset cols="200,*">


    <frameset rows="30%,70%>


Frames 4
Frames (4)

  • Inside framesets the only permitted tags are other framesets, frames and noframes.

  • Frame tag defines the actual frames. It takes arguments like SRC, MarginWidth, Scrolling etc.

  • noframes tag provide alternate content for browsers not having frames capability

Frames 5
Frames (5)

  • Sample frame scripting


    <frameset rows="50%,*">

    <frame src="">

    <frame src="">



Frames 6
Frames (6)

  • Frames with name tag:

    <title>WebQuiz using JavaScript</title>

    <frameset cols=60%,*>

    <frame src="webQuiz.htm" name="main">

    <frame src="webAnsw.htm" name="hello">


  • Hypertext reference with a “Target” tag:

    <h3>Correct Answers</h3>

    <A href="webAnsw.htm#a1" Target="hello">#1</a>

Hidden object
Hidden Object

  • A text object that is suppressed from form display on an HTML form. A hidden object is used for passing name/value pairs when a form submits.

  • Typically used with CGI scripts to pass special data between the browser and the server

  • Value is reset when the document is reloaded (unlike other form elements)

Hidden object cont d
Hidden Object (cont’d)

  • Example:

    // uses a hidden object to store the value of the last object the user clicked

    FileName: hidden.htm

    <FORM NAME="form1">

    <INPUT TYPE="hidden" NAME="hiddenObject" VALUE="None">

    <P><INPUT TYPE="button" VALUE="Click me" NAME="button1"


    <P><INPUT TYPE="radio" NAME="musicChoice" VALUE="jazz"

    onClick="document.form1.hiddenObject.value=this.value"> Jazz

    <P><INPUT TYPE="button" VALUE="Display hidden value" NAME="button2" onClick="alert('Last object clicked: ' + document.form1.hiddenObject.value)">


Image object images array
Image Object / Images Array

  • Image array called document.images

    • created for all images defined by <IMG>

    • each is an Image object

    • use: document.images[0],document.images[1], etc.

    • can dynamically change the content of graphics

      • document.images[0].src = “”;

Location object
Location Object

  • Contains information on the current URL

  • Use this object to set or get the URL of a window or frame

  • Properties

    • same as the ones in link object

  • Methods: None.

  • Event handlers: None.

  • Property of: document

Location object 2
Location Object (2)

  • Examples:

    • // sets the URL of the current window to the Netscape home page:

      • window.location.href=“”

        or simply

      • document.location=“”

    • // sets the URL of a frame named frame2 to the Sun home page:

      • parent.frame2.location.href=""

Navigator object
Navigator Object

  • Use the navigator object to determine which version of the Navigator your users have.

  • Properties

    • appCodeName specifies the code name of the browser

    • appName specifies the name of the browser

    • appVersion specifies version information for the Navigator

    • userAgent specifies the user-agent header

  • Methods: None.

  • Event handlers: None.

  • Property of: None.

  • Example:

    • alert(“This version of Netscape is “ + navigator.appVersion)

Radio object
Radio Object

  • A set of radio buttons on an HTML form, allowing the user choose one item from a list.

  • All radio buttons in a radio button group use the samename property.

  • To access the individual radio buttons, follow the object name with an index starting from zero

    • document.forms[0].radioName[0] is the first radio button, document.forms[0].radioName[1] is the second, etc.

    • or myForm.radioName[0], etc. // access a form using its name

Radio object 2
Radio Object (2)

  • Properties

    • checked lets you programatically select a radio button and check if a radio button is checked or not.

    • defaultChecked reflects the CHECKED attribute

    • length reflects the number of radio buttons in a radio object

    • name reflects the NAME attribute

    • value reflects the VALUE attribute

  • Methods: click

  • Event handlers: onClick

  • Property of: form

This means that you can check which

radio button is selected by doing:

if (myForm.musicChoice[0].checked == true)

… // first radio button is checked

Radio object 3
Radio Object (3)

  • Examples

    FileName: radio.htm

    <form name=musicForm>

    <INPUT TYPE="radio" NAME="musicChoice" VALUE="soul-and-r&b"

    onClick="musicForm.catalog.value = 'soul-and-r&b'"> Soul and R&B

    <INPUT TYPE="radio" NAME="musicChoice" VALUE="jazz"

    onClick="musicForm.catalog.value = 'jazz'"> Jazz

    <INPUT TYPE="radio" NAME="musicChoice" VALUE="classical"

    onClick="musicForm.catalog.value = 'classical'"> Classical

    <BR> Selected Music:

    <INPUT TYPE="text" NAME="catalog" SIZE="20">


Radio object 4
Radio Object (4)

  • Example:

    Submit form using a server program (a home-made Java servlet called EchoAll)

    FileName: radio2.htm

    <form name=musicForm method="get" action="">

    <INPUT TYPE="radio" NAME="musicChoice" VALUE="soul-and-r&b" onClick="musicForm.catalog.value = 'soul-and-r&b'"> Soul<br>

    <INPUT TYPE="radio" NAME="musicChoice" VALUE="jazz" onClick="musicForm.catalog.value = 'jazz'"> Jazz<br>

    <INPUT TYPE="radio" NAME="musicChoice" VALUE="classical" onClick="musicForm.catalog.value = 'classical'"> Classical<br>


    Selected Music: <INPUT TYPE="text" NAME="catalog" SIZE="20">

    <input type="submit">


Select object options array
Select Object (Options Array)

  • A selection (“drop-down”) list or scrolling list on an HTML form. A selection list lets the user choose one item from a list. A scrolling list lets the user choose one or more items from a list.

  • Properties

    • The select object has the following properties:

      • length reflects the number of options in a select object

      • name reflects the NAME attribute

      • options reflects the <OPTION> tags

      • selectedIndex reflects the index of the selected option (or the first selected option, if multiple options are selected)

Select object options array 2
Select Object (Options Array) (2)

  • The options array has the following properties:

    • defaultSelected reflects the SELECTED attribute

    • index reflects the index of an option

    • length reflects the number of options in a select object

    • name reflects the NAME attribute

    • selected lets you programatically select an option

    • selectedIndex reflects the index of the selected option

    • text reflects the textToDisplay that follows an <OPTION> tag

    • value reflects the VALUE attribute

Select object options array 3
Select Object (Options Array) (3)

  • Example:

    FileName: select.htm

    // Displays a selection list and a scrolling list. Then shows the selections.


    function testSelect(form) {

    index = form.music_type_single.selectedIndex

    alert(form.music_type_single.options[index].text+" and "+





    Choose the music type for your free CD:

    <SELECT NAME="music_type_single">



    <P>Choose the music types for your free CDs:

    <BR><SELECT NAME="music_type_multi" MULTIPLE>



    <P><INPUT TYPE="BUTTON" NAME="Button" VALUE="ClickMe"



String object
String Object

  • A series of characters.

  • Properties

    • length reflects the length of the string

  • Methods

    • anchor, big, blink, bold, charAt, fixed, fontcolor, fontsize, indexOf, italics, lastIndexOf, link, small, strike, sub, substring, sup, toLowerCase, toUpperCase

  • Event handlers: None.

  • Property of: None.

String object 2
String Object (2)

  • Examples

    • The following statement creates a string variable.

      • var last_name = "Schaefer"

      • last_name.length // gives 8

      • last_name.toUpperCase() // gives “SCHAEFER”

      • last_name.toLowerCase() // gives “schaefer”

      • last_name.indexOf(“e”) // gives 4

      • last_name.indexOf(“x”) // gives –1 (for not found)

      • last_name.substring(2,5) // gives “hae” (1st index is inclusive, 2nd index is exclusive)

      • last_name.substr(1,4) // gives “chae” (starting at 1, extract 4 chars)

      • last_name.charAt(1) // gives “c” (not “S”)

  • Question: What if you need the 2nd “e” on the string? (Answer: check out the API for a method. Let’s see …)

Submit object
Submit Object

  • A submit button on an HTML form. A submit button causes a form to be submitted.

  • Example:

    FileName: submit.htm

    // With JavaScript, can get the user the confirm before submitting a form.


    function submitMe(form) {

    if (confirm(“Are you sure you want to submit this form?”))

    return (true)


    return (false)



    <form onSubmit=“return submitMe(this)”

    method="get" action="">


    <INPUT TYPE="submit">


true => form is submitted

false => submit process is aborted

Text object
Text Object

  • A text input field on an HTML form. A text field lets the user enter a word, phrase, or series of numbers.

  • Text objects can be updated (redrawn) dynamically by setting the value property (this.value).

  • Properties

    • defaultValue reflects the VALUE attribute

    • name reflects the NAME attribute

    • value reflects the current value of the text object's field

Text object 2
Text Object (2)

  • Examples:

    • FileName: text.htm

      // creates a text object that is 25 characters long. The text field appears immediately to the right of the words "Last name:". The text field is blank when the form loads.

      <B>Last name:</B> <INPUT TYPE="text" NAME="last_name" VALUE="" SIZE=25>

      // creates two text objects on a form. Each object has a default value. The city object has an onFocus event handler that selects all the text in the field when the user tabs to that field. The state object has an onChange event handler that forces the value to upper case.

      <FORM NAME="form1">

      <BR><B>City: </B><INPUT TYPE="text" NAME="city" VALUE="Anchorage"

      SIZE="20" onFocus="">

      <B>State: </B><INPUT TYPE="text" NAME="state" VALUE="AK" SIZE="2"



Textarea object
Textarea Object

  • A multiline input field on an HTML form. A textarea field lets the user enter words, phrases, or numbers.

  • Properties

    • defaultValue reflects the VALUE attribute

    • name reflects the NAME attribute

    • value reflects the current value of the text object's field

  • Methods

    • focus, blur, select

Textarea object 2
Textarea Object (2)

  • Event handlers

    • onBlur

    • onChange

    • onFocus

    • onSelect

  • Property of

    • form

Window object
Window Object

  • The top-level object for each document, location, and history object group.

  • To define a window, use the open method:

    • var myWin ="URL", "windowName"



      var myWin =“", “Window1”,“height=300,width=400,toolbar=yes,scrollbar=yes")

No space!!!

Window object 2
Window Object (2)

  • Properties

    • defaultStatus reflects the default message displayed in the window's status bar

    • frames is an array reflecting all the frames in a window

    • length reflects the number of frames in a parent window

    • name reflects the windowName argument

    • parent is a synonym for the windowName argument and refers to a window containing a frameset

    • self is a synonym for the windowName argument and refers to the current window

    • status specifies a priority or transient message in the window's status bar

    • top is a synonym for the windowName argument and refers to the top-most Navigator window

    • window is a synonym for the windowName argument and refers to the current window

Window object 3
Window Object (3)

  • Methods

    • alert

    • close

    • confirm

    • open

    • prompt

    • setTimeout

    • clearTimeout

  • Event handlers

    • onLoad

    • onUnload

  • Property of

    • None.

Window object 4
Window Object (4)

  • Example:

    • In the following example, the document in the top window opens a second window, window2, and defines pushbuttons that open a message window, write to the message window, close the message window, and close window2. The onLoad and onUnload event handlers of the document loaded into window2 display alerts when the window opens and closes.

    • WIN1.HTM, which defines the frames for the first window, contains the following code:



      <TITLE>Window object example: Window 1</TITLE>


      <BODY BGCOLOR="antiquewhite">


      window2=open("win2.htm","secondWindow","scrollbars=yes,width=250, height=400")

      document.writeln("<B>The first window has no name: " + + "</B>")

      document.writeln("<BR><B>The second window is named: " + + "</B>")


Window object 5
Window Object (5)

<FORM NAME="form1">

<P><INPUT TYPE="button" VALUE="Open a message window"

onClick="'','messageWindow','scrollbars=yes,width=175, height=300')">

<P><INPUT TYPE="button" VALUE="Write to the message window"

onClick="window3.document.writeln('Hey there');window3.document.close()">

<P><INPUT TYPE="button" VALUE="Close the message window"


<P><INPUT TYPE="button" VALUE="Close window2"





Window object 6
Window Object (6)

  • WIN2.HTM, which defines the content for window2, contains the following code:



    <TITLE>Window object example: Window 2</TITLE>


    <BODY BGCOLOR="oldlace"

    onLoad="alert('Message from ' + + ': Hello, World.')"

    onUnload="alert('Message from ' + + ': I\'m closing')">

    <B>Some numbers</B>






Event handling1
Event Handling

  • JavaScript provides a moderate level of event detection to pass control to functions attached to built-in event handlers

  • e.g.,

    • <INPUT type=“button” VALUE=“button1”

    • onClick=“computeSomething()”>

  • Events are triggered in the browser primarily by user actions such as button click, page load, form submit.

Event handlers
Event Handlers

  • The following event handlers are available in JavaScript:

    • onAbort

    • onBlur

    • onChange

    • onClick

    • onDragDrop

    • onError

    • onFocus

    • onKeyDown

    • onKeyPress

    • onKeyUp

    • onLoad

  • onMouseDown

  • onMouseMove

  • onMouseOut

  • onMouseOver

  • onMouseUp

  • onMove

  • onReset

  • onResize

  • onSelect

  • onSubmit

  • onUnload

Event handlers cont
Event Handlers (Cont...)

  • onAbort

    • An abort event occurs when a user aborts the loading of an image (for example by clicking a link or clicking the Stop button)

  • onBlur

    • A blur event occurs when a select, text, or textarea field on a form loses focus.

  • onChange

    • A change event occurs when a select, text, or textarea field loses focus and its value has been modified.

  • onClick

    • A click event occurs when an object on a form is clicked.

Event handlers cont1
Event Handlers (Cont...)

  • onDragDrop

    • A drapDrop event occurs when a user drops an object onto the browser window, such as dropping a file on the browser window

  • onError

    • An error event occurs when the loading of a document or image causes an error

  • onFocus

    • A focus event occurs when a field receives input focus by tabbing with the keyboard or clicking with the mouse.

  • onKeyDown, onKeyPress, onKeyUp

    • A keyDown, keyPress, or keyUp event occurs when a user depresses a key, presses or holds down a key, or releases a key, respectively

Event handlers cont2
Event Handlers (Cont...)

  • onLoad

    • A load event occurs when Navigator finishes loading a window or all frames within a <FRAMESET>.

    • Examples

      • In the following example, the onLoad event handler displays a greeting message after a web page is loaded.

      • <BODY onLoad="window.alert('Welcome to my home page!')">

  • onMouseDown, onMouseMove, onMouseOut, onMouseOver, and onMouseUp

    • A MouseDown, MouseMove, MouseOut, MouseOver, or MouseUp event occurs when a user depresses a mouse button, moves a cursor, moves a cursor out of a link or image map, moves a cursor over a link, releases a mouse button, respectively

Event handlers cont3
Event Handlers (Cont...)

  • onMouseOver

    • A mouseOver event occurs once each time the mouse pointer moves over an object from outside that object.

  • Example

    <A HREF=""

    onMouseOver="window.status=‘A Good Place …!'; return true">

    Click me</A>

Return true tells the browser not to perform its own

event handling routine of displaying the link’s URL

in the status bar

Event handlers cont4
Event Handlers (Cont...)

  • onSelect

    • A select event occurs when a user selects some of the text within a text or textarea field.

  • onSubmit

    • A submit event occurs when a user submits a form

  • onUnload

    • An unload event occurs when you exit a document.

Form validation

FileName: valid2.htm

<html><head><script language="JavaScript">

function test1(form) {

if (form.text1.value == "")

alert("Please enter a string!")

else {

alert("Hi "+form.text1.value+"! Form input ok!");



function test2(form) {

if (form.text2.value == "" ||

form.text2.value.indexOf('@') == -1)

alert("No valid e-mail address!");

else alert("OK!");


// -->



<form name="first">

Enter your name:<br>

<input type="text" name="text1">

<input type="button" name="button1" value="Test Input" onClick="test1(this.form)">


Enter your e-mail address:<br>

<input type="text" name="text2">

<input type="button" name="button2" value="Test Input" onClick="test2(this.form)">


Form Validation

Form validation 2

FileName: Ex-valid.htm




function checkit() {

var strval = document.myform.mytext.value;

var intval = parseInt(strval);

if ( intval > 0 && intval < 10 ) {


} else {

alert("Input value " + strval + " is out of range");






<HR><FORM NAME="myform"></P>

<P>Enter a number between 1 and 9: <INPUT TYPE="text" NAME="mytext" VALUE="" SIZE="10"></P>


<INPUT TYPE=“button“onClick="checkit()“></FORM>




Form Validation (2)

Form validation 3

FileName: testNaN.htm

// Shows NaN and the use of isNaN()



<script language="JavaScript">

function test2(form) {

var ans = parseInt(form.text2.value);

if (isNaN(ans))

alert("NaN (Not A Number)!");

else alert("OK!");






Enter a number:<br>

<input type="text" name="text2">

<input type="button" name="button2" value="Test Input" onclick="test2(this.form)">




Form Validation (3)

This function returns true if the 1st digit can be

parsed into a number. Otherwise, it returns false.

More features
More Features

  • JavaScript Library: ability to define a separate page for the JavaScript program

    • <SCRIPT SRC=“library.js”>

      • js extension

      • do not need </SCRIPT> tag

      • can include JavaSript code in <SCRIPT> and </SCRIPT> tags

    • new <NOSCRIPT>and </NOSCRIPT> tags

      • contents ignored by JavaScript but processed as HTML


  • Client-Side JavaScript Guide, Netscape Communications Inc., 1998

  • Client-Side JavaScript Reference, Netscape Communications Inc., 1998

  • Hall, M., Core Web Programming, Prentice-Hall, 1998.

  • Voodoo’s Introduction to JavaScript, 1998.

  • Shin, S., JavaScript Basics,