CMPS 335 Advanced Web Publishing
JavaScript Programming
Understanding JavaScript Objects
Object-oriented programming is about constructing programs
from objects. In traditional object-oriented languages
, such as Java and C++, data and procedures are contained in a structure
known as a class. Class acts as a templet from which
any number of instances can be created. These instances are objects
and they inherit all the data and procedures of that class.
JavaScript also supports objects. Like a variable, an object
can store data, but it can store multiple pieces of data at once.
The items of data stored in an object are called properties of the
object. A property is basically a variable that contains the data of
the object and it can be assigned a value. An object can also
contain procedures called methods. A method is a function
that is called from within the object. In JavaScript, all procedures
are functions. JavaScript supports there categories of objects:
- Browser objects -- Window, Document, Image, and Form.
These objects are created by the browser to represent various
components of the browser and the current HTML document.
- Built-in objects -- String, Array, Date, and Math.
These objects are built into the JavaScript language. They
exist in JavaScript independently of the host environment.
- Custom objects
JavaScript provides the capability for your to define your own
object types and create specific object instances.
Each built-in object has a special function called constructor
function that can be used to create new objects. To create a String,
Array, or Date object, you must first create an instance of it in memory
using the new keyword. For example, you can create a string
object using one of the following statements:
studentName = new String();
studentName = new String("David Anderson");
You can use the same basic syntax to create Array objects and Date objects.
The Math object is an exception. You dont't need to create a
Math object, because it exists automatically in any JavaScript script.
When you create a new object from a constructor
function, you are instantiating a new object. An object is a special
kind of a variable that can store properties and methods. A JavaScript
object is instantiated from a constructor function and it inherits
all the properties and methods of the constructor function.
A variable can have either numeric or string value. It can
also be either global or local in its scope. Global
variables are declared outside of functions and are available to all parts
of the program. Local variables are declared inside functions
and are available only within the functions in which they are declared.
Object-Manipulation Statements
The this keyword always refers to the current object. The
for-in statement is a special form of loop that loops through the
properties of a particular object from first to last and has the
following syntax:
for (variable in objectname) {
statement(s);
}
The with statement eliminates the need to retype the name of an
object when properties of the same object are being referenced in a
series. You create the with statement by using the following
syntax:
with (objectname) {
statement(s);
}
JavaScript Events and Event Handlers
One of the primary ways in which JavaScript makes HTML documents
dynamic and interactive is through events and event handlers. An
event handler is a JavaScript script that responds to a specific event
such as a mouse click. Event handlers are associated with particular
browser objects. An event handler is specified as an attribute to
the HTML tag that defines the object. Event handlers have the same
name as the event, preceded by the word on. For example:
<input type="button" name="calculate"
onClick="compute(form1);">
Some Important JavaScript Events
Event Triggered When
----------------------------------------------------------
abort The loading of an image is interrupted
blur An element becomes inactive
click An element is click once
change The value of an element changes
error There is an error loading a doc. or image
focus An element becomes active
load A document or image loads
mouseOut The mouse moves off an element
mouseOver The mouse moves over an element
reset A form resets
select A user selects a field in a form
submit A user submits a form
Examples of onMouseOver and onMouseOut Event Handlers
<script language=JavaScript>
var message1 = "Do Not Click Me!";
var message2 = "Thanks for Leaving Me Alone.";
</script
<br><a href="cmps235.html"
onMouseOver="window.status='Do Not Click Me'; return true"
onMouseOut="window.status='Thanks for Leaving Me Alone';
return true">Don't Touch Me!</a>
<br><a href="cmps235.html"
onMouseOver="window.status=message1; return true"
onMouseOut ="window.status=message2; return true">
Don't Touch Me 2</a>
<!-- Using window.alert instead of window.status -->
<br><a href="cmps235.html"
onMouseOver="window.alert('Do Not Click Me')"
onMouseOut="window.alert('Thanks for Leaving Me Alone')">
Don't Touch Me 3</a>
<br><a href="cmps235.html"
onMouseOver="window.status='Advanced Web Publishing';
return true"
onMouseOut="window.status=' '; return true">[cs 491]</a>
Click Here for onMouseOver
examples
Hierarchy of Browser Objects
When a Web page is loaded by a JavaScript-capable browser, the
browser creates a number of JavaScript objects as the results of the Web
page you design. These objects are used to access, update, and
interact with the Web page and the elememnts it contains. Each object
represents part of the Web page. An object may contain other
objects. The browser window in which an HTML document is displayed
is modeled with the Window object.
The Window object contains the document property that refers to the
Document object. A document may contain a form and the form object
provides access to the individual elements defined via the elements
property. The elements array refers to button, checkbox, hidden,
password, radio, reset, select, submit, text, and textarea
form fields. These form elements are also objects.
Browser objects are orgarnized into hierarchy of parent and child objects as
shown below:
| | anchors[ ]
window -> | document -> |
| | forms[ ] -> form elements
| |
| | images[ ]
| |
| | links[ ]
|
| history
|
| location
In JavaScript, every object can be given a name and referred to in the
script code using dot syntax as shown in the following example:
if (form.operator.value == "add") {
form.answer.value = parseFloat(form.num1.value) +
parseFloat(form.num2.value);
}
Important Objects and Their Properties, and Methods
Array
Properties: length
Methods: pop, push, sort
Event Handlers: none
Date
Properties: none
Methods: getDate, getDay, getFullYear, getHours, getMonth
getMinutes, getTime, toLocaleString. toGMTString
Event Handlers: none
Document
Properties: alinkColor, anchors, applets, bgColor, cookie
fgColor, form, forms, image, images, lastModified,
links, location, title, vlinkColor
Methods: clear, close, open, write, writeln
Event Handlers: none
Form
Properties: action, Button, Checkbox, elements, Hidden,
length, method, name, Password, Radio, Reset,
Select, Submit, target, Text, Textarea
Methods: reset, submit
Event Handlers: onReset, onSubmit
Global
Properties: Infinity, NaN
Methods: eval, isFinite, isNaN, parseFloat, parseInt
History
Properties: current, length, next, previous
Methods: back, forward, go
Image
Properties: border, complete, height, hspace, name, src, width
Methods: none
Event Handlers: onAbort, onError, onLoad
Link
Properties: host, hostname, href, pathname, target
Methods: none
Event Handlers: onClick, onMouseover, onMouseout
location
Properties: host, hostname, href, pathname, ...
Methods: reload, replace
Event Handlers: none
Math
Properties: E, LN2, LN10, ...
Methods: abs, cos, exp, log, max, min, pow, random,
round, sin, sqrt, tan
Event Handlers: none
navigator
Properties: appName, appVersion, platform, plugins, ...
Methods: javaEnabled, preference, ...
Event Handlers: none
Password
Properties: defaultValue, form, name, value, ...
Methods: blur, focus, select
Event Handlers: onBlur, onChange, onFocus, onKeydown,
onKeypress, onKeyup, onSelect
Radio
Properties: checked, defaultChecked, form, name, value
Methods: blur, focus, select
Event Handlers: onClick, onMousedown, onMouseup
Select
Properties: form, length, name, options, selectedIndex
Methods: blur, focus
Event Handlers: onChange
screen
Properties: availHeight, availWidth, height, width
Methods: none
Event Handlers: none
String
Properties: length
Methods: big, blink, bold, charAt, concat, fontcolor,
fontsize, indexOf, italics, small, stike, sub,
substring, sup, toLowerCase, toUpperCase, ...
Event Handlers: none
Submit
Properties: form, name, value
Methods: blur, click, focus
Event Handlers: onClick, onMousedown, onMouseup
Text
Properties: defaultValue, form, name, value
Methods: blur, focus, select
Event Handlers: onBlur, onChange, onFocus, onKeydown,
onKeypress, onKeyup, onSelect
window
Properties: document, frames, history, length, location,
name, parent, self, status, top, ...
Methods: alert, close, confirm, open, prompt
setInterval, setTimeout
Event Handlers: onBlur, onError, onFocus, onLoad, onResize
The Window Object
Browser objects represent various parts of the browser window and the
current document. The window object is at the top of the
hierarchy. Some of the frequently referneced window properties and
metrhods are shown below:
Properties: document, history, location
Methods: alert, close, confirm, open, prompt
The alert, confirm, and prompt methods are used to display message boxes
for communication between JavaScript and Web page visitors. These
important window methods have already been described in the chapter of
JavaScript Basics.
The Document Object
The document property of the window object is a reference to the
Document object. The document object has several properties and
methods. The write method serves as script output to dynamically
create HTML code. The syntax of the write method is:
document.write(expression11 [,...,expressionN]};
If the parameter to the write method consists of several strings separated
by commas, they are catenated together.
The History Object
The history property of the window object is a reference to the
History object. The History object maintains a history of all the
documents that have been opened during the current browser session.
The History object has the following methods:
Method Description
-------- -----------------------------------------------------
back() Equivalent to clicking the browser's Back button
forward() Equivalent to clicking the browser's Forward button
go() Opens a URL from the history list
history.go(-1) and history.go(1) are equivalent to history.back and
history.forward, respectively, as shown in the following example:
<a href="javascript:history.go(-1);"><img border=0
src="left.gif"></a>
<a href="javascript:history.go(1);"><img border=0
src="right.gif"></a>
The Location Object
The location property of the window object is a reference to the
Location object. The location object stores information about the
current URL. For example, the following statement loads a URL into
the current window:
window.location.href = "http://www.fbchammond.org";
The String Object
To create an instance of the built-in String object, use any
of the following statements:
- Using a regular variable assignment statement
str1= "Compter Science";
String variables are actually String objects. The second
way uses the official object syntax.
- Using the constructor function
str2= new String("Computer Science");
str3= new String();
Some Important String Object Methods
- charAt(index)
Returns the character at the specified position in a text string.
- fontsize(size)
Adds a <FONT SIZE=size> tag pair to a text string
- indexOf(text,index)
Returns the position number in a string of the first character in
the text argument. If the index argument is included, then the
function starts searching at the position within the string.
Returns -1 if the text is not found.
- substring(starting_index, ending_index)
Extracts text from a string
Examples
<script language=JavaScript>
string1 = "Southeastern Louisiana University";
string2 = new String("Southeastern Louisiana University");
document.write("<br>"+ string1);
document.write("<br>"+ string2);
string4 = string2.charAt(6);
document.write("<br>"+ string4);
string5 = string2.fontsize(2);
document.write("<br>"+ string5);
string6 = string2.toLowerCase();
document.write("<br>"+ string6);
string7 = string2.indexOf("east");
document.write("<br>"+ string7);
string8 = string2.indexOf("ebst");
document.write("<br>"+ string8);
string9 = string2.substring(13,22);
document.write("<br>"+ string9);
document.write("<br>"+ string1.toUpperCase());
document.write("<br>"+ string1.bold());
document.write("<br>"+ string1.fontcolor("red"));
</script>
Output
Southeastern Louisiana University
33
33
a
Southeastern Louisiana University
southeastern louisiana university
5
-1
Lousiana
SOUTHEASTERN LOUISIANA UNIVERSITY
Southeastern Louisiana University
Southeastern Louisiana University
Click Here for Date objects examples
The Global Object
There are two constant properties for global object: NaN and
Infinity. The NaN constant means not a number and the
Infinity property represents positive infinity. Methods
defined for the Global object are as follows:
eval(expression): Returns the value of the expression
isNaN(expression): Returns true if the expression is not a number
parseFloat(string): Returns a floating-point numeric value
parseInt(string): Returns an integer numeric value
Return to CMPS 335 Home Page
Return to Web Site Home Page