What Is Javascript?: Javascript Is Interpreted by The Browser. Js Code Is Typically Embedded Right in HTML Pages
What Is Javascript?: Javascript Is Interpreted by The Browser. Js Code Is Typically Embedded Right in HTML Pages
Overview
What is JavaScript?
Object-oriented concepts
Properties are where the objects store their data, and are
generally the attributes that you get or set.
Methods contain the various functions that can operate on an
object
Events are actions recognized by an object, such as a mouse
moving over it, or the user clicking on an object, such as a link.
Versions of JavaScript
Alternatives to JavaScript
JavaScript Basics
A typical script:
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide script from old browsers.
document.write("Hello, net!")
...more JavaScript...
// End the hiding here. -->
</SCRIPT>
JavaScript comments
Variable names
o Can only have alphanumeric characters plus the underscore
character (_)
o They can not start with a digit
o Can't use reserved JavaScript keywords either
o Sample variable names:
Valid names: count, Count, try1, num, showMessages,
table_index, i, j, k
Invalid variable names: count$, my-name, 2cows
variable_name
var variable_name = "Hello" // -- preferred
message1 = "Hello" // -- is OK too
var count=100
<NOSCRIPT>
Please use a browser with JavaScript enabled to view
this document.
</NOSCRIPT>
Selective JavaScript version snippets
<SCRIPT LANGUAGE="JavaScript1.1">
<!-- Run on JavaScript 1.1 browsers only
document.write("...from JavaScript 1.1")
...more JavaScript...
// End the hiding here. -->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript1.2">
<!-- Run on JavaScript 1.2 browsers only
document.write("...from JavaScript 1.2")
...more JavaScript...
// End the hiding here. -->
</SCRIPT>
Data Types
Numbers
dec_number = 255 // -- decimal is default
hex_number = 0xff // -- hex value of FF (255)
fp_number = 2.456 // -- Floating point number
Boolean operators
A boolean value can only be true or false.
Character strings
NOTE: User input entered via a form element is usually read as a string. If
you need to use it as a number, you need to first convert it with the
parseInt or parseFloat built-in function
myStrVar = "24"
myIntegerVar = parseInt(myStrVar)
myStrVar = "24.75"
myFloatVar = parseFloat(myStrVar)
() e.g. 5*(4+5)
++ e.g. ++1 or 1++
-- e.g. --1 or 1--
*, /, %, =, -, and so forth
String operators
String1 = 'Java'
String2 = 'Script'
// -- Concatenate to get "JavaScript"
String3 = String1 + String2
Conditionals
The if/else statement requires a boolean expression to decide
between two alternative actions.
if (x > 0) {
document.writeln("x is positive");
}
else {
document.writeln("x is negative");
}
var n = 5
document.write("n! of ", n);
var fact =1;
// -- Compute n factorial (n!)
// -- where n is a non-negative integer
while (n > 1) {
fact = fact * n
n = n -1
}
document.writeln(" is ", fact);
Functions
JavaScript, like most programming languages, has facilities for creating
subprograms to modularize or divide programs into distinct functions. When
required, a function can be called to carry a particular task. In general,
functions in JavaScript should be placed in the <HEAD> portion of the
document to ensure that they are loaded before they are called.
function max(a,b) {
// -- Multiple Returns
if (a > b)
return(a); // -- Return a
else
return(b); // -- Return b
}
function verifyEmail(email) {
/* -- Description: Checks for valid email addresses.
Arguments: email - a string with an email address.
Returns: false if any field is deemed invalid;
true otherwise */
if ((email.indexOf ('@', 0) == -1 ||
(email.indexOf ('.', 0) == -1)) {
// -- An email address should contain at least
// -- one at-sign (@) and one period(.).
alert("Enter your Email address");
return false
}
return true;
}
...
<FORM NAME="signup" ACTION="..." METHOD=POST
onSubmit="return verifyEmail(signup.txtEmail.value)">
Email Address:
<INPUT TYPE="text" NAME=txtEmail VALUE="" SIZE=40>
<INPUT TYPE="submit" NAME="submit1" VALUE="Submit">
</FORM>
Arrays in JavaScript
Arrays are used to store numbered pieces of data. Each piece of data is
called an element, and the number assigned to is is called its index.
Defining arrays
Properties are the values belonging to the objects. A property may be of any
type. A property may be an object itself with its own set of properties.
The dot notation is normally used to access the properties from an object.
The object names go on the left, while the property name goes on the right.
object-name.property-name
Examples:
o navigator.appName /* -- browser name, e.g. Netscape or MSIE */
o document.URL // -- complete document URL
o document.bgColor="indigo" /* -- changes the background color */
JavaScript has many built-in objects; they all follow a given hierarchy.
The most important ones are:
Referring to windows
form1.username.value = 'Wednesday'
window.document.form1.username.value="Michael Jordan"
parent.frame1.document.form1.username.value = "Delores Jordan "
win1.document.bgColor = "#FFFFFF" // -- i.e. white background
win1.win2.document.fgColor = "#0000FF" // -- blue foreground
close() - closes it
confirm() - prompts for OK|Cancel, returns true|false
e.g. confirm("Go ahead and download 100 megabyte movie?")
The window object's document object contains information about the current
document being displayed on the browser's window. The most common
properties are:
There are a handful of document methods. The most important ones are:
A built-in object containing information about the browser that has loaded
the document. Its properties are very useful in detecting the type of browser
in use, its configuration and plug-in availability. The navigator properties
are:
Besides their traditional use, functions in JavaScript can be used not just as
object methods, but also as constructors and event handlers.
Methods are also specified using the dot notation, with the object
name(s) on the left and the method or function name on the right,
with parameters enclosed in parentheses.
function function-name(parameter-list) {
...
body of the function
...
}
JavaScript Events
Examples
Reload a page:
Form validation:
<form name="name" onsubmit="JS function()">
e.g.
<form name="name" onSubmit="return testAge()">
<input type="text" name="ageBox"><p>
<input type="submit" name="submit">
</form>
Quick & easy JavaScript programs
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- begin hiding...
var Initials = "EdG" //-- Put your initials
between the quotes
document.write("Last Modified: ")
document.write(document.lastModified)
document.write(" " + Initials)
// -- stop hiding -->
</SCRIPT>
<HEAD>
<TITLE>Redirection Example</TITLE>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- begin hiding...
function redirect() {
if (confirm('We have moved. Click OK
to go to our new home')) {
location="http://www.uic.edu/depts/adn/itl";
}
}
// -- stop hiding -->
</SCRIPT>
</HEAD>
<BODY onLoad="redirect()">
<form>
<input type=button" value="<- 2 Pages"
onClick="history.go(-2)">
<input type=button" value="Previous Page"
onClick="history.go(-1)">
<input type=button" value="Next Page"
onClick="history.go(1)">
<input type=button" value="2 Pages ->"
onClick="history.go(2)">
</form>
<a href="hell.html"
onMouseOver="window.status='This link
will take you to hell';
return true">Hell Web Page</a>
if (navigator.appName == "Netscape") {
if (navigator.appVersion.indexOf("Win95")
!= -1) {
if
(navigator.appVersion.indexOf("4") != -1) {
// -- we have Nestcape 4.0 or later
on Win95
}
}
}
Dynamic HTML
Some examples
Browser requirements:
o Netscape Communicator
4.x or
o Microsoft Internet
Explorer (MSIE) 4.x
o Some examples work on
either
Macromedia DHTMLzone
(both)
o http://www.dhtmlzone.
com
Project Cool (both)
o http://www.projectcool.
com
Incognito Media (both)
o http://www.ina.com/~l
am
Microsoft Gallery (MSIE
only)
o http://www.microsoft.c
om/gallery/files/html
What is Dynamic
HTML?
A collection of Web
technologies
o including brand new
HTML 4.0 W3C standard
HTML plus...
Cascading Style Sheets
(CSS1)
Cascading Style Sheet
Positioning
Document Object Model
(DOM)
o DHTML object model
Dynamic re-drawing of
any part of a Web page
New intra-object event-
handling capabilities
Client-side
Processing/Scripting
o JavaScript
o Microsoft JScript
o ECMAscipt
o Microsoft VBScript
o Microsoft ActiveX
o Java
Dynamic fonts and
canvas mode
Data Binding &
Awareness
What is DHTML
good for?
Develop dynamic Web
pages
o Plug-in free animations
o Web page (3D) layering
o Tight graphics control
o Create special effects
o Change custom pages
on-the-fly
Tighter look-and-feel
control
Typesetting-like
positioning
Easier to develop
consistent Web pages
Exploit client computer
processing power
HTML extensibility (inc.
XML)
Dynamic HTML
Authoring Tools
Macromedia DreamWeaver -
rave reviews
Microsoft FrontPage 98 -
great!, but MSIE-biased
Astound Dynamite
NetObjects Fusion and
ScriptBuilder - soon
DHTML Issues
Too new, still evolving...
(as of Spr'98)
Requires Netscape or
MSIE 4.x browsers
Many differences
between Netscape and
MSIE
o They will adhere to
W3C recommendations
7828454217