0% found this document useful (0 votes)
116 views

What Is Javascript?: Javascript Is Interpreted by The Browser. Js Code Is Typically Embedded Right in HTML Pages

The document provides an overview of the JavaScript programming language, covering its syntax, objects, properties, events, functions, and coding techniques. The seminar discusses when and why to use JavaScript and emphasizes its importance in HTML and Dynamic HTML standards. Prerequisites include familiarity with HTML and some programming experience.

Uploaded by

Arun Tripathi
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
116 views

What Is Javascript?: Javascript Is Interpreted by The Browser. Js Code Is Typically Embedded Right in HTML Pages

The document provides an overview of the JavaScript programming language, covering its syntax, objects, properties, events, functions, and coding techniques. The seminar discusses when and why to use JavaScript and emphasizes its importance in HTML and Dynamic HTML standards. Prerequisites include familiarity with HTML and some programming experience.

Uploaded by

Arun Tripathi
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

JavaScript is a programming language well-suited for creating powerful, interactive

hypermedia. This seminar provides a thorough overview of the JavaScript language


syntax, objects, properties, events, and functions, along with coding techniques and
examples. We discuss why/when one would choose JavaScript and emphasize its
importance in HTML 4 and Dynamic HTML standards. Prerequisites: HTML
familiarity and some programming experience.

Overview

What is JavaScript?

JavaScript (JS) is an object-based programing language.

 JavaScript is interpreted by the browser. JS code is typically


embedded right in HTML pages
 JavaScript programs are written using objects, which have
properties, associated data and behavior (methods) belonging to
them.
 JavaScript provides various objects and methods or functions,
and you can create new ones.

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.

A real world example:

 Consider a speaker phone as an object


 Property: speaker phone volume. telephone.speakerVolume=2
 Method: dialing the telephone. telephone.dial("312-413-0003")
 Event: the phone is ringing. ring(callerName)

What else is JavaScript?


 JavaScript is not Java
 JavaScript is relatively easy to learn
 It is a scripting language
 JavaScript enables client-side processing
 JS programs are built into the Web page in the form of a script.

Versions of JavaScript

 JavaScript 1.0 (Netscape 2.0)


 JavaScript 1.1 (Netscape 3.x, MSIE 4.x)
 JavaScript 1.2 (Netscape Communicator 4.0 to 4.04)
 JavaScript 1.3 (Netscape Comunicator 4.06 or later)
 Microsoft JScript ~ JavaScript 1.1
 WWW Consortium standard: ECMA-262 JavaScript ~ JavaScript 1.1

What is JavaScript good for?

 Generating on-the-fly Web pages or HTML


 Facilitating user interaction with Web pages
 Adding programming control to HTML
 Client-side processing
 Validating fields in HTML forms
 Detecting browsers and browser environment
 Opening and managing browser windows and frames
 Programming navigation buttons
 Key component of Dynamic HTML
 Java and Plug-in interface and control via LiveConnect
 Dressing up your Web pages

Alternatives to JavaScript

 Java, CGI scripts, VBScript, ActiveX controls


 Plug-ins like Flash, Shockwave and other proprietary plug-ins
 Other scripting languages like Lingo and PHP

JavaScript Language Syntax

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

// for inline comments and /* ... */ for multi-line comments

 Statement separator - semicolon (;).


Only needed to separate multiple statements on the same line.

 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

 JavaScript is very case-sensitive

 Declaration and assignment statements

variable_name
var variable_name = "Hello" // -- preferred
message1 = "Hello" // -- is OK too
var count=100

 NoScript tag - to notify users or take different action if JavaScript


is not available or enabled.

<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

var mystring = "University"


emailaddress = '[email protected]'
thisYear = "1998"
myQuote = "Let's do it!"
 

 Data type conversion


JavaScript is a loose type language
 var myval = "water" // -- myval initialized
 myval = true // -- myval is boolean true
myval = 98 // -- now myval has an integer

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)

 Operator precedence – the usual

() 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");
}

 The for loop


The for loop instructs the computer to repeat a piece of code, a
specific number of times.

for (initial, condition-check, increment)


for (j=1, j<10, j++) {
document.writeln("This is loop#", j);
}

 The while loop


Simply loops until some condition is true.

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);

 Also, break, continue and labels; plus, Do While and Switch in


JavaScript 1.2.

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.

Why should you use functions?

 To exploit reusable code


 They are easier to debug and test
 Functions are much easier to maintain
 They help you write clean structured programs

JavaScript functions behave a little differently than you might


expect:

 There is no value/reference distinction


 There is no data type distinction
 Return values do not have data types and are optional!
A couple of examples

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.

JavaScript arrays are very similar to conventional arrays in other


programming languages, but there are some differences:

 An element of an array can be of any type (character string, integer,


Boolean, another array)
 Different elements of the same array may be of different types
 The first element of an array is at index 0.
 JS arrays can be sparse -- i.e. they can contain non-contiguous
elements
 JS arrays are objects so they have properties like length, and built-in
methods like join, reverse and sort.

Defining arrays

 Arrays can be created like you create objects


o myArray = new Object()
o myArray[0] = 1
o myArray[1] = 2 ...

 You can create them with a constructor


o a = new EmptyArray(32)
o a = new Array()
o anotherArray = new Array(16)

 Define and initialize them at once


o a = new Array(1, 2, 3, "HTML", "MSIE")

Using array elements

 Reading and writing


o value = a[0]
o a[1] = "Dynamic HTML"
o i = 2; a[i] = "Macromedia DreamWeaver"
o a[i + 1] = "Allaire HomeSite 4.0"
o a [10] = a[1]
o myTools[visual] = "GoLive CyberStudio"
o myTools[html] = "Lightning HTML Editor"
o myTools[email] = "Qualcomm Eudora"
o myTools[graphics] = "Adobe Photoshop"

 Adding new elements


o a[0] = 0
o a[1000] = [-1]

 Multi-demensional arrays - array of arrays


o myTable[state][city] = "The big Apple"
JavaScript Objects and Properties

Objects are a fundamental part of JavaScript. An object is a data type that


contains named pieces of data, i.e. properties.

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:

 The window object - browser windowing, at the highest level


 The document object - of the document being displayed
 The navigator object - stores browser environment characteristics
 The forms object - holds HTML forms info
 The history object - holds browser's history (visited links)

Before using an object, an instance of it must be created. An object class is


a definition/blueprint of an object. Instances are used for creating objects.

 Some instances are created automatically, e.g. the document object


 Others have to be created explicitly, e.g. the Date object;
namely, var today = new Date()

The window object

The window object is created automatically, when the browser opens a


window. Commonly-used window object properties include:

 name - window's name


 opener - name of window that opened this window
 self - synonym for current window or frame
 status - text in the status bar
onMouseOver = "status='See site map';return true;"
self.status = "Calculation complete."
 innerHeight - height of document area, in pixels, JS1.2 only
 innerWidth - width of document area, JS1.2 only
 length - number of frames in window

Window properties that are objects are:

 document - currently displayed document


 frame - object with info about frame(s)
 history - history list of current frame or window
 location - URL info of current document.
use window.location="http://..." to redirect
 screen - allows us to find out screen resolution (width and height) in pixels!
New in JS1.2, however.

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

Window Object Methods

 alert() - post small dialog box on the screen


e.g. alert("Please enter a valid email address")

 blur() - moves focus away from specified window


 setTimeout() - specifies a delay, in milliseconds
 clearTimeout() - cancels delay

 open() - opens a window


o syntax: open("url","win-name","options")
o sample window open method

 close() - closes it
 confirm() - prompts for OK|Cancel, returns true|false
e.g. confirm("Go ahead and download 100 megabyte movie?")

 prompt() - small dialog box prompting for a character string


e.g. prompt("Enter loan amount")

 back() - browser Back button, JS1.2


Better to use history.go(-1) instead.
 find() - opens browser search dialog box, JS1.2
 forward(), home(), stop(), print() -- all JS1.2

The document object

The window object's document object contains information about the current
document being displayed on the browser's window. The most common
properties are:

 bgColor - the document's background color


e.g. document.bgColor = "#00FF00"
 Applet - an <APPLET tag, used to embed a Java applet into a document
 domain - domain name of Web server
 fgColor - the document's foreground color
 ids - IDs to use in <STYLE> tags for Dynamic HTML (JS1.2)
 location - URL of the currently displayed document

Document object methods

There are a handful of document methods. The most important ones are:

 write() - writes text (inc. HTML) to document


e.g. document.write("<H2>Related Links</H2> blah <P>blah ...")

 writeln() - writes text to document, ending with a newline character

The navigator object

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:

 appCodeName - browser's code name


e.g. "Mozilla" (even for MSIE :-)

 appName - browser's (long) name


e.g. "Netscape", "Microsoft Internet Explorer"

 appVersion - browser's version


e.g. "4.04 [en] (Win95;I)", "4.0 (compatible; MSIE 4.0; Windows 95)"
e.g. if (navigator.appVersion.indexOf("4.") > 0 ...

 MimeType - an object containing a MIME type that can be handled by the


browser
 mimeTypes - an array of MimeType objects
 platform - operating system for which browser was compiled (JS1.2)
 Plugin - an object with info about an installed plug-in viewer
 plugins - an array of plug-ins installed in the browser
e.g. shocked = (nagivator.plugins["Shockwave"] != null)

There are only two navigator methods, one of which is javaEnabled() -


which returns a Boolean value indicating whether Java has been enabled in
the browser.

Methods and Functions

Methods and Functions

Methods are behaviors applied on objects. Different objects have different


methods available. Additional methods may be created, by writing
appropriate JavaScript functions.

Besides their traditional use, functions in JavaScript can be used not just as
object methods, but also as constructors and event handlers.

Method and function invocation

 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.

 Parentheses are always required even when no parameters are used.


o object-name.method-name(parameters)
o object-name.function-name(parameters)
o document.write("Hello there") // -- write method

o var sometext = "Hi Ed";


UpperCasedText = sometext.toUpper()

 When used as an event handler, a function is called in a traditional


assignment invocation; examples:
o <BODY onload="checkBrowser()">

o <A HREF="somewhere.junk.html onclick="confirm('Are you sure?')">Click


here to visit the Junk site</A>

o <A HREF="javascript:justDoit(foo,env,mon)">Apply changes</A>

Defining a function in JavaScript

This is similar as in most other languages, namely:

function function-name(parameter-list) {
...
body of the function
...
}

where parameter-list is the list of parameters, separated by commas. The


values are assigned to the function local variables named (within
parentheses), passed by name.

Data type and number of of arguments are not checked in JavaScript. A


return statement is also optional.

JavaScript Events

JavaScript uses an event-driven programming model to interface with the


graphical environment of the Web browser. Event handler functions are
usually written to perform a task or set of tasks when an event occurs.

 JavaScript code is typically executed when the user does something.


o Automatic events: when a page loads or unloads
o Explicit events: when the user clicks, submits, tabs, moves the
mouse, etc..

 Event handlers are placed inside HTML tags

<tag attributes event-handler="JS code">

 Event handlers can be case-sensitive. In general, use lower case.


 Event handler JS function code usually goes in <head> section, which
executes before onload event.

Tag-specific event handlers

 onLoad and onUnload - in <body> (and <img> in JS1.1)

 onClick - on links and in button, checkbox, radio, reset and submit


form elements

 onBlur - when focus moves away from a form element


 onChange - focus away from form elem. after a change
 onFocus - when focus moves to the form element

 onMouseOver - when mouse pointer moves over a link (image) -


useful for "rollover effects".
 onMouseOut - when mouse pointer moves away from link (image) -
typically used in conjunction with onMouseOver for rollover effects.

 onSelect - when user selects something from a form


 onSubmit - when user clicks the submit button
This is the preferred way of validating forms.

 New JavaScript 1.2 events:


o onMove - when user moves frame or window
o onSize - when user resizes a frame or window
o onKeyUp, onKeyDown, onKeyPress
o onMouseDown, onMouseMove, onMouseUp

Examples

 Reload a page:

if (Confirm("Want to reload? Click OK")) {


history.go(0)
}

 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

The following are some quick and easy things


that you can do to enhance your pages without
knowing much about JavaScript.

Displaying "Last Modified" date on


your Web pages

Stick the following script at the end of your


Web pages to automatically display the
date when they were last modified. You can
also put your initials between the quotation
marks, on line 3 to have them show up
right after the date.

<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>

The lastModified document property


actually returns the date and time, in the
form of MM/DD/YY hh:mm:ss. To display
only the date, we could apply the
substring method (function) to the
lastModified character string, namely:
document.lastModified.substring(0,8)

Take people to your new home

The following script will come in handy to


redirect people to your new home page.

<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()">

Confirm returns true if you click the OK


button, and false if you press Cancel. The
if statement will only let the location
assignment redirection execute if Confirm
returns true. Notice how the redirect()
function is defined in the <HEAD> portion
of the page. The onLoad event is used in
the <BODY> tag to trigger a call to
redirect() as soon as the page finishes
loading.

Warn people before clicking on a


link

In this example, we make use of the


onClick event handler to prompt the users
for a confirmation before chasing a given
link. The link might require Java or a
special Plug-in that the users might not
have. Note that since we are using an
event handler, the following is just plain
HTML code embedded anywhere in the
document, i.e. without the need for a
<SCRIPT> tag.

<a href="some-dangerous-URL" onClick="return


confirm('Are you sure you want to visit this
site?')">Bleeding Edge Site</a>

Providing additional navigation


buttons

JavaScript provides a variety of navigation


controls. You could use the following script
to add custom Back and Forward buttons
anywhere on your document; these buttons
would carry out the same function and their
counterparts found on the toolbar. Again,
since we are using an event handler, the
JavaScript code does not need to be
enclosed within the <SCRIPT> tag.

<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>

The onClick event handler tells the


browser what to do when the user clicks on
a button: the browser executes history.go
to go through the history list. -2 means go
back to pages, 2 means go forward two
pages, and so forth.

Status Bar Messages

Status bar messages is something that


people use a lot, mostly because they are
easy to implement. In this example, we use
the onMouseOver event to trigger the
time when to write on the status bar. When
the mouse pointer moves over the link, the
status bar message will be displayed.
windows.status requires that we include
the return true statement.

<a href="hell.html"
onMouseOver="window.status='This link
will take you to hell';
return true">Hell Web Page</a>

One link to update two frames


<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- begin hiding...
function updateFrames(){
parent.frame1.location = 'http://...'
parent.frame2.location = 'http://...'
}
// -- stop hiding -->
</SCRIPT>
<a href='javascript:updateFrame()'>a
link</a>

Let's try it.

Looking at the browser


characteristics
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide script from old browsers.
// -- Traverse the navigator object and
display its properties
for (prop in navigator) {
document.write("&nbsp;&nbsp;" +
navigator
+ "." + prop + " = " +
navigator[prop] + "<br>");
}
// -- End the hiding here. -->
</SCRIPT>

Let's try it.

Likewise, one can easily test for browser


characteristics, like browser name, version,
platform. Here are some examples:

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

You might also like