JavaScript - PowerPoint PPT Presentation

1 / 89
About This Presentation
Title:

JavaScript

Description:

The word var is optional (but it's good style to use it) ... var course = new Course('CS450', 'Dr. ABC'); 30 /89. Array literals ... var colors = new Array(3) ... – PowerPoint PPT presentation

Number of Views:67
Avg rating:3.0/5.0
Slides: 90
Provided by: Suka2
Category:
Tags: javascript | var

less

Transcript and Presenter's Notes

Title: JavaScript


1
JavaScript
Source http//www.ccse.kfupm.edu.sa/mibuhari/swe
444/SWE444.htm
2
Overview
  • A "scripting" language for HTML pages - a
    scripting language is a lightweight programming
    language
  • Embed code in HTML pages so they are downloaded
    directly to browser
  • The browser interprets and executes the script
    (it is not compiled)
  • Was designed to add interactivity to HTML pages
  • Everyone can use JavaScript without purchasing a
    license
  • Supported by all major browsers

3
Overview
  • Do not declare data types for variables (loose
    typing)
  • Dynamic binding object references checked at
    runtime
  • Scripts can manipulate "browser objects"
  • HTML form elements
  • Images
  • Frames
  • etc.
  • For security cannot write to disk (when run on
    a client)

4
Abilities
  • Generating HTML content dynamically
  • Monitoring and responding to user events
  • Validate forms before submission
  • Manipulate HTTP cookies
  • Interact with the frames and windows of the
    browser
  • Customize pages to suit users

5
It is not Java
  • JavaScript is not Java, or even related to Java
  • The original name for JavaScript was LiveScript
  • The name was changed when Java became popular
  • Released in the Fall of 1995
  • Statements in JavaScript resemble statements in
    Java, because both languages borrowed heavily
    from the C language
  • JavaScript should be fairly easy for Java
    programmers to learn
  • JavaScript is seldom used to write complete
    programs
  • Instead, small bits of JavaScript are used to add
    functionality to HTML pages
  • JavaScript is often used in conjunction with HTML
    forms
  • JavaScript is reasonably platform-independent

6
It is not Java
  • JavaScript has some features that resemble
    features in Java
  • JavaScript has Objects and primitive data types
  • JavaScript has qualified names for example,
    document.write("Hello World")
  • JavaScript has Events and event handlers
  • Exception handling in JavaScript is almost the
    same as in Java
  • JavaScript has some features unlike anything in
    Java
  • Variable names are untyped the type of a
    variable depends on the value it is currently
    holding
  • Objects and arrays are defined in quite a
    different way
  • JavaScript has with statements and a new kind of
    for statement

7
Scripting
  • The entire script is stored in memory as plain
    text
  • When requested by the user the applicable portion
    of the script is executed by fetching the
    associated machine instructions from a library
  • Tends to be a bit slower than compiling programs
  • However, there is no burden on the author to
    compile anything
  • Errors are not obvious when scripting only
    rigorous testing will find errors

8
History
  • Built into Netscape Navigator since v2.0 (early
    1996)
  • Developed independently of Java
  • Proprietary, but submitted as standard and built
    into Microsoft IE 3.0 and later
  • Standardized by ECMA (European Computer
    Manufactures Association) into ECMAscript
  • EMCAscript joins JavaScript and Jscript to one
    standard

9
Javascript has many names
  • In Netscape its Javascript
  • In Internet Explorer its JScript
  • IE also supports its own VB Script, a Visual
    Basic scripting language
  • VB Script wont work in Netscape
  • There is also ECMAscript
  • A variation of Javascript 1.1
  • Open Standard
  • Promoted by European Computer Manufacturers
    Association (ECMA)
  • JScript is essentially ECMAscript in IE 4.0

10
Javascript Versions
  • 1.0 Original version, largely obsolete
  • Supported in Navigator 2.0
  • Buggy version of it supported in IE 3.0 as
    JScript
  • 1.1
  • Improved array processing
  • Supported in Navigator 3.0 as JScript, some
    discrepancies
  • 1.2
  • Supports regular expressions, new statements
  • Supported in Navigator 4.0
  • 1.3
  • Fixed some problems with dates, introduced in
    Navigator 4.06
  • ECMAScript
  • First supported in IE 4.0, also in Navigator 4.06
  • Largely the same as Javascript 1.1

11
Dynamic HTML
HTML
CSS
Java Script
Java Script
HTML
HTML
CSS
HTML
12
Web Architecture for JavaScript
"CLIENT"
"SERVER"
Desktop access
Remote host
Web browser
Web (HTTP) Server
HTML Page ltSCRIPTgt code.. lt/SCRIPTgt
Internet
HTML/HTTP TCP/IP
HTML/HTTP TCP/IP
built-in JavaScript interpreter
HTML pages w/ embedded script
13
Client and Server
  • JavaScript can be used
  • On the client side
  • On the server
  • More lightweight and reliable on clients than
    Java (Applets)
  • Useful for developing interactive interface
    (Dynamic HTML)

14
Sample Things you can Do with JavaScript
  • Auto email
  • Rename a button
  • Change background color
  • View URL
  • Set timer
  • Open a window
  • Display date

15
Sample Things you can Do with JavaScript
  • Print page
  • Save and access a cookie
  • Sniff the browser
  • Data validation
  • Print a page
  • Preload images
  • Flyout/Dropdown menus

16
Example
  • JavaScript code is included within ltscriptgt tags
  • ltscript type"text/javascript"gt
    document.write("lth1gtHello World!lt/h1gt")
    lt/scriptgt
  • Notes
  • The type attribute is to allow you to use other
    scripting languages (but JavaScript is the
    default)
  • This simple code does the same thing as just
    putting lth1gtHello World!lt/h1gt in the same place
    in the HTML document
  • The semicolon at the end of the JavaScript
    statement is optional
  • You need semicolons if you put two or more
    statements on the same line
  • Its probably a good idea to keep using
    semicolons

17
Dealing with old browsers
  • Some old browsers do not recognize script tags
  • These browsers will ignore the script tags but
    will display the included JavaScript
  • To get old browsers to ignore the whole thing,
    use ltscript type"text/javascript"gt
    lt!-- document.write("Hello World!")
    //--gt lt/scriptgt
  • The lt!-- introduces an HTML comment
  • To get JavaScript to ignore the HTML close
    comment, --gt, the // starts a JavaScript comment,
    which extends to the end of the line

18
Where to put JavaScript
  • JavaScript can be put in the ltheadgt or in the
    ltbodygt of an HTML document
  • JavaScript functions should be defined in the
    ltheadgt
  • This ensures that the function is loaded before
    it is needed
  • JavaScript in the ltbodygt will be executed as the
    page loads
  • JavaScript can be put in a separate .js file
  • ltscript src"myJavaScriptFile.js"gtlt/scriptgt
  • Put this HTML wherever you would put the actual
    JavaScript code
  • An external .js file lets you use the same
    JavaScript on multiple HTML pages
  • The external .js file cannot itself contain a
    ltscriptgt tag
  • JavaScript can be put in HTML form object, such
    as a button
  • This JavaScript will be executed when the form
    object is used

19
Primitive data types
  • JavaScript has three primitive types number,
    string, and boolean
  • Everything else is an object
  • Numbers are always stored as floating-point
    values
  • Hexadecimal numbers begin with 0x
  • Some platforms treat 0123 as octal, others treat
    it as decimal
  • Strings may be enclosed in single quotes or
    double quotes
  • Strings can contains \n (newline), \" (double
    quote), etc.
  • Booleans are either true or false
  • 0, "0", empty strings, undefined, null, and NaN
    are false, other values are true

20
Variables
  • Variables are declared with a var statement
  • var pi 3.1416, x, y, name "Dr. ABC"
  • Variables names must begin with a letter or
    underscore
  • Variable names are case-sensitive
  • Variables are untyped (they can hold values of
    any type)
  • The word var is optional (but its good style to
    use it)
  • Variables declared within a function are local to
    that function (accessible only within that
    function)
  • Variables declared outside a function are global
    (accessible from anywhere on the page)

21
Operators, I
  • Because most JavaScript syntax is borrowed from C
    (and is therefore just like Java), we wont spend
    much time on it
  • Arithmetic operators - /
    --
  • Comparison operators lt lt !
    gt gt
  • Logical operators ! (
    and are short-circuit operators)
  • Bitwise operators
    ltlt gtgt gtgtgt
  • Assignment operators - /
    ltlt gtgt gtgtgt

22
Operators, II
  • String operator
  • The conditional operator condition ?
    value_if_true value_if_false
  • Special equality tests
  • and ! try to convert their operands to the
    same type before performing the test
  • and ! consider their operands unequal if
    they are of different types
  • Additional operators new typeof void
    delete

23
Comments
  • Comments are as in C or Java
  • Between // and the end of the line
  • Between / and /

24
Statements, I
  • Most JavaScript statements are also borrowed from
    C
  • Assignment greeting "Hello, " name
  • Compound statement statement ...
    statement
  • If statements if (condition) statement
    if (condition) statement else statement
  • Familiar loop statements while (condition)
    statement do statement while (condition)
    for (initialization condition increment)
    statement

25
Statements, II
  • The switch statement switch (expression)
    case label statement
    break case label statement
    break ... default
    statement
  • Other familiar statements
  • break
  • continue
  • The empty statement, as in or

26
Exception handling, I
  • Exception handling in JavaScript is almost the
    same as in Java
  • throw expression creates and throws an exception
  • The expression is the value of the exception, and
    can be of any type (often, it's a literal String)
  • try statements to try catch (e) //
    Notice no type declaration for e
    exception-handling statements finally //
    optional, as usual code that is always
    executed
  • With this form, there is only one catch clause

27
Exception handling, II
  • try statements to try catch (e if test1)
    exception-handling for the case that test1
    is true catch (e if test2)
    exception-handling for when test1 is false and
    test2 is true catch (e)
    exception-handling for when both test1 and test2
    are false finally // optional, as
    usual code that is always executed
  • Typically, the test would be something like
    e "InvalidNameException"

28
Object literals
  • You dont declare the types of variables in
    JavaScript
  • JavaScript has object literals, written with this
    syntax
  • name1 value1 , ... , nameN valueN
  • Example
  • car myCar "Toyota", 7 "Mazda",
    getCar CarTypes("Honda"), special Sales
  • The fields are myCar, getCar, 7 (this is a legal
    field name) , and special
  • "Toyota" and "Mazda" are Strings
  • CarTypes is a function call
  • Sales is a variable you defined earlier
  • Example use document.write("I own a "
    car.myCar)

29
Three ways to create an object
  • You can use an object literal
  • var course number CS450", teacher"Dr. ABC"
  • You can use new to create a blank object, and
    add fields to it later
  • var course new Object()course.number
    CS450"course.teacher "Dr. ABC"
  • You can write and use a constructor
  • function Course(n, t) // best placed in
    ltheadgt this.number n this.teacher
    t
  • var course new Course(CS450", "Dr. ABC")

30
Array literals
  • You dont declare the types of variables in
    JavaScript
  • JavaScript has array literals, written with
    brackets and commas
  • Example color "red", "yellow", "green",
    "blue"
  • Arrays are zero-based color0 is "red"
  • If you put two commas in a row, the array has an
    empty element in that location
  • Example color "red", , , "green", "blue"
  • color has 5 elements
  • However, a single comma at the end is ignored
  • Example color "red", , , "green", "blue,
    still has 5 elements

31
Four ways to create an array
  • You can use an array literal var colors
    "red", "green", "blue"
  • You can use new Array() to create an empty array
  • var colors new Array()
  • You can add elements to the array
    latercolors0 "red" colors2 "blue"
    colors1"green"
  • You can use new Array(n) with a single numeric
    argument to create an array of that size
  • var colors new Array(3)
  • You can use new Array() with two or more
    arguments to create an array containing those
    values
  • var colors new Array("red","green", "blue")

32
The length of an array
  • If myArray is an array, its length is given by
    myArray.length
  • Array length can be changed by assignment beyond
    the current length
  • Example var myArray new Array(5) myArray10
    3
  • Arrays are sparse, that is, space is only
    allocated for elements that have been assigned a
    value
  • Example myArray50000 3 is perfectly OK
  • But indices must be between 0 and 232-1
  • As in C and Java, there are no two-dimensional
    arrays but you can have an array of arrays
    myArray53

33
Arrays and objects
  • Arrays are objects
  • car myCar Toyota", 7 "Mazda"
  • car7 is the same as car.7
  • car.myCar is the same as car"myCar"
  • If you know the name of a property, you can use
    dot notation car.myCar
  • If you dont know the name of a property, but you
    have it in a variable (or can compute it), you
    must use array notation car."my" "Car"

34
Array functions
  • If myArray is an array,
  • myArray.sort() sorts the array alphabetically
  • myArray.sort(function(a, b) return a - b )
    sorts numerically
  • myArray.reverse() reverses the array elements
  • myArray.push() adds any number of new elements
    to the end of the array, and increases the
    arrays length
  • myArray.pop() removes and returns the last
    element of the array, and decrements the arrays
    length
  • myArray.toString() returns a string containing
    the values of the array elements, separated by
    commas

35
The forin statement
  • You can loop through all the properties of an
    object with for (variable in object) statement
  • Example for (var prop in course)
    document.write(prop " " courseprop)
  • Possible output teacher Dr. ABC
    number CS450
  • The properties are accessed in an undefined order
  • If you add or delete properties of the object
    within the loop, it is undefined whether the loop
    will visit those properties
  • Arrays are objects applied to an array, forin
    will visit the properties 0, 1, 2,
  • Notice that course"teacher" is equivalent to
    course.teacher
  • You must use brackets if the property name is in
    a variable

36
Functions
  • Functions should be defined in the ltheadgt of an
    HTML page, to ensure that they are loaded first
  • The syntax for defining a function isfunction
    name(arg1, , argN) statements
  • The function may contain return value statements
  • Any variables declared within the function are
    local to it
  • The syntax for calling a function is just
    name(arg1, , argN)
  • Simple parameters are passed by value, objects
    are passed by reference

37
Regular expressions
  • A regular expression can be written in either of
    two ways
  • Within slashes, such as re /abc/
  • With a constructor, such as re new
    RegExp("abc")
  • Regular expressions are almost the same as in
    Perl or Java (only a few unusual features are
    missing)
  • string.match(regexp) searches string for an
    occurrence of regexp
  • It returns null if nothing is found
  • If regexp has the g (global search) flag set,
    match returns an array of matched substrings
  • If g is not set, match returns an array whose 0th
    element is the matched text, extra elements are
    the parenthesized subexpressions, and the index
    property is the start position of the matched
    substring

38
Debugging
  • If you mess up on the syntax you will get a
    Javascript Error
  • Netscape
  • You will see a notification of an error on the
    status bar in the bottom left corner
  • You type javascript in the URL field to
    pinpoint the error
  • Internet Explorer
  • By default a tiny little Javascript error message
    appears at the bottom left corner of the browser
    in yellow. Usually you wont see it.
  • Can be explicitly disabled under Tools/Internet
    Options
  • Recommend under Tools/Internet Options/Advanced/Br
    owsing to uncheck Disable Script Debugging and
    to check Display a Notification about every
    script error while doing development

39
Fixing Javascript Errors
  • If possible use the debugging tool to locate the
    line containing the error
  • Errors can be hard to find and fix
  • code a little, test a little strategy
  • Often errors are due to things that are easy to
    overlook, like not closing a quote

40
Numbers
  • In JavaScript, all numbers are floating point
  • Special predefined numbers
  • Infinity, Number.POSITIVE_INFINITY -- the result
    of dividing a positive number by zero
  • Number.NEGATIVE_INFINITY -- the result of
    dividing a negative number by zero
  • NaN, Number.NaN (Not a Number) -- the result of
    dividing 0/0
  • NaN is unequal to everything, even itself
  • There is a global isNaN() function
  • Number.MAX_VALUE -- the largest representable
    number
  • Number.MIN_VALUE -- the smallest (closest to
    zero) representable number

41
Strings and characters
  • In JavaScript, string is a primitive type
  • Strings are surrounded by either single quotes or
    double quotes
  • There is no character type
  • Special characters are

\0 NUL \b backspace \f form feed \n
newline \r carriage return \t horizontal tab
\v vertical tab \' single quote \"
double quote \\ backslash \xDD Unicode hex
DD \xDDDD Unicode hex DDDD
42
Some string methods
  • charAt(n)
  • Returns the nth character of a string
  • concat(string1, ..., stringN)
  • Concatenates the string arguments to the
    recipient string
  • indexOf(substring)
  • Returns the position of the first character of
    substring in the recipient string, or -1 if not
    found
  • indexOf(substring, start)
  • Returns the position of the first character of
    substring in the given string that begins at or
    after position start, or -1 if not found
  • lastIndexOf(substring), lastIndexOf(substring,
    start)
  • Like indexOf, but searching starts from the end
    of the recipient string

43
More string methods
  • match(regexp)
  • Returns an array containing the results, or null
    if no match is found
  • On a successful match
  • If g (global) is set, the array contains the
    matched substrings
  • If g is not set
  • Array location 0 contains the matched text
  • Locations 1... contain text matched by
    parenthesized groups
  • The array index property gives the first matched
    position
  • replace(regexp, replacement)
  • Returns a new string that has the matched
    substring replaced with the replacement
  • search(regexp)
  • Returns the position of the first matched
    substring in the given string, or -1 if not
    found.

44
boolean
  • The boolean values are true and false
  • When converted to a boolean, the following values
    are also false
  • 0
  • "0" and '0'
  • the empty string, '' or ""
  • undefined
  • null
  • NaN

45
Arrays
  • As in C and Java, there are no true
    multidimensional arrays
  • However, an array can contain arrays
  • The syntax for array reference is as in C and
    Java
  • Example
  • var a "red", 255, "green", 128
  • var b a10 // b is now "green"
  • var c a1 // c is now "green", 128
  • var d c1 // d is now 128

46
Input
  • Programming languages need to start with some
    data and manipulate it
  • Confirm asks a yes or no question in a dialog box
  • Prompt prompts the user to type in some
    information into a text field inside the dialog
    box
  • Sources of data can include
  • Files
  • Databases
  • User (keyboard mouse typically)
  • Variable assignments (ex pi3.14159)
  • Javascript objects
  • Example date object
  • Example
  • User_name prompt(What is your name?, Enter
    your name here)

47
Output
  • After a program manipulates the input data with
    various statements it usually creates an output
    of some kind
  • Source of output may include
  • Files
  • Database
  • Display or Printer
  • Devices (sound card, modems etc)
  • Javascript Objects
  • Via Object Methods

48
Simple Output
  • document is an object (not a class) representing
    the current document
  • write is a method on the document object that
    lets you write any text to the browser window at
    the current location of the cursor
  • Warning if invoked as part of a form action
    output will appear in a new window
  • Example
  • document.write(Hello world!)

49
alert method
  • A dialog box containing information can be
    written by using the window.alert method
  • Example
  • alert(This brings up an annoying non-modal
    dialog box. The user cant do anything until they
    click OK.)

50
HTML names in JavaScript
  • In HTML the window is the global object
  • It is assumed that all variables are properties
    of this object, or of some object decended from
    this object
  • The most important window property is document
  • HTML form elements can be referred to by
    document.formsformNumber.elementselementNumber
  • Every HTML form element has a name attribute
  • The name can be used in place of the array
    reference
  • Hence, if
  • ltform name"myForm"gt ltinput type"button"
    name"myButton" ...gt
  • Then instead of document.forms0.elements0
  • you can say document.myForm.myButton

51
Document Object Model (DOM)
  • Document Object Model
  • The Dynamic HTML Document Object Model in this
    case
  • There are other DOMs
  • It allows a document (in this case the web
    browser) to be manipulated as multiple objects
  • For example, the document with focus in the
    browser is the document object
  • You manipulate properties of the objects by
    setting object properties and calling methods of
    objects

52
DOM Object Hierarchy
53
Navigating through the DOM
  • 5 objects have predefined names that cant be
    changed and are available to any page
  • window, document, history, location, navigator
  • Any object of a type that can be replicated is
    accessed by the HTML name or ID attribute.
  • Ex ltform nameform1gt
  • Accessed by window.document.form1
  • If an object is named uniquely it is not
    necessary to give a fully qualified name
  • Ex use form1 instead of window.document.form1
  • Objects that are not named may be accessed
    indirectly through an array. Element 0 indicates
    the number of objects
  • Ex document.forms1 or forms1

54
Javascript object example
  • Document
  • Properties
  • fgcolor specifies color of document text
  • same as ltbody textcolorgt
  • Methods
  • clear erases contents of current document
  • write sends text to the browser

55
Math Object
  • Can be accessed as Math.property, ex
  • xMath.pow(3,3) // x27
  • Allows many common mathematical calculations
    including
  • abs(x) absolute value
  • ceil(x) and floor(x) smallest integer not less
    than x and largest integer not greater than x
  • cos(x), exp(x), log(x), sin(x), tan(x)
    trigonometric and log rhythmic functions
  • min(x,y) or max(x,y) returns the minimum or
    maximum of values x and y
  • pow(x,y) raises x to the power y
  • round(x) rounds to nearest integer
  • sqrt(x) Square root

56
Date Object
  • By default creates an object with the computers
    current date and time, ex
  • now new Date() // variable now contains
    current date and time
  • Note months are expressed 0-11, 0 being January,
    11 being December
  • Dates are actually stored as an integer
    representing the number of milliseconds since
    January 1st, 1970
  • Negative values indicate dates before this date
  • Once you have a date object you can set the date,
    or read the date in a number of useful formats
  • now.setFullYear(2003, 0, 31) / Jan 31st, 2003
    /
  • Now.setHours(13, 13, 13) / 11313 PM, local
    time zone /

57
Date Properties
  • Some of the more useful properties of the date
    class include
  • now.getDay() / returns 0-6 for the day of the
    week, 0Sunday, 6Saturday /
  • now.getFullYear() / year of this date object /
  • now.getMonth() / 0-11 returned for the current
    month /
  • now.getDate() / 1-31 for the day in the month
    /
  • now.getHours() / 0-23, may need to translate to
    PM /
  • now.getMinutes() / 1-60 /
  • Now.getSeconds() / 1-60 /

58
Window Object
  • The window object is the master DOM object at
    the top of the DOM hierarchy
  • Useful properties
  • length number of frames in window
  • frames an array of window objects, one for each
    frame
  • parent Since frames are window objects,
    sometimes parent window is needed
  • Examples
  • window.document if frameless, accesses the top
    level document. If frames, accesses the top
    frames document
  • window.frame1.document Access the document
    contained in the first frame
  • frame1.parent.document Access the document
    contained in the parent frame

59
Window Object Methods
  • alert, confirm and prompt are actually methods of
    the window object, ex window.alert
  • window.open() / opens a window /
  • window.close() / closes window /

60
Navigator Object
  • Contains information about the browser
  • Can be accessed as window.navigator or just
    navigator
  • Useful properties
  • appName name of browser used (can be deceiving
    more on this in a later class)
  • appVersion version of browser used (can be
    deceiving more on this in a later class)
  • platform operating system in use
  • cookieEnabled can the browser store cookies?

61
Location Object
  • Contains information about the current URL
  • Can be accessed as window.location or just
    location
  • Useful properties
  • href retrieves entire URL
  • host retrieves just the domain name (ex
    yahoo.com)
  • pathname retrieves just the path inside the
    domain (page name is at end)
  • hash retrieves the anchor

62
History Object
  • Contains information on the URLs that the browser
    has visited in this session within a window
  • Can be accessed as window.history or just history
  • Useful properties next, previous (tells you the
    URL, but wont direct you there)
  • Useful methods
  • back same as pressing the back arrow button
  • forward same as pressing the forward arrow
    button
  • go go back or forward a given number of pages
    to go back 3 pages
  • history.go(-3)

63
Document Object
  • This is the typically the most accessed object
  • You can access all items in the document window
    through the document object
  • Forms, tables, paragraphs, lists, images, etc.
  • Consult a reference for properties and methods
  • Frameless document Access as window.document or
    document
  • Document contained in a frame window.framex.doc
    ument, where x is the number or name of the frame

64
DOM Collections
  • Inside objects may be one or more collections of
    child objects
  • Syntax object.collection
  • object is either a standard object (like
    document) or the HTML ID attribute that uniquely
    identifies an item on a page
  • collection is a group of objects all of the same
    type
  • Ex document.links
  • document is the DOM object
  • links is a collection of link objects inside the
    document object
  • The document object may have many links embedded
    inside of it (just as a page may have many links
    in it)
  • The collection of links can be thought of as an
    array of link objects, i.e. links0, links1
    etc.

65
Addressing DOM Collections
  • Collection objects anchors, applets, embeds,
    forms, frames, images, links, plugins, scripts,
    styleSheets
  • Addressing an element in a collection can be done
    in a number of ways. Pick the way easiest for
    you
  • document.collectioni
  • i is a number, 0 thru n where n is the last
    element in the collection array and 0 the first
  • Ex document.links0 references the first link
    on the page
  • Use this if there was no HTML ID attribute
    assigned to an element
  • document.collection.id
  • id is the HTML ID attribute of the object
  • HTML lta hrefa.htm idBgtLinklt/agt
  • DOM reference (using IE) document.all.B
  • document.collectionid
  • HTML lta hrefa.htm idBgtLinklt/agt
  • DOM reference document.allB

66
Addressing blocks by ID
  • Assume tag ltdiv idXgt lt/divgt
  • IE
  • document.all.id
  • Ex document.all.X
  • or just
  • id
  • Ex X
  • Mozilla/Netscape 6 find by ID, ex
  • handle document.getElementById("X")
  • // Now use the handle variable to access
    properties

67
Cross platform code
  • Sometimes you have to write one set of code that
    will work for both browsers
  • Here is a sample technique
  • var isNS false
  • var isIE false
  • if (!(document.all)) isNStrue
  • if (document.all) isIEtrue
  • if (isNS)
  • el document.getElementById("X")
  • el.setAttribute("style",
    "background-colorpink")
  • if (isIE)
  • document.all.X.style.backgroundColor"pi
    nk"

68
Events
  • Most browser DOM objects have events associated
    with them
  • Recall Javascript objects include windows,
    frames, forms, form fields, links, etc.
  • An event is Javascript code that can be triggered
    when something happens to a Javascript object
  • Example clicking on a hyperlink
  • Example leaving a form field

69
Events
  • Event code is usually invoked through HTML
    Javascript only attributes
  • They are not HTML attributes
  • They are not in the HTML specification
  • However, if Javascript is enabled and the event
    is valid for the Javascript object then
    associated code is executed.
  • Example
  • ltform nametest onsubmitreturn validate()gt

70
Events
  • Some events will behave differently depending on
    whether the code associated with the event
    returns a true or a false value
  • Example If the form onsubmit event returns
    false, the form is not submitted
  • All events start with on, ex onclick,
    onsubmit, etc. This makes them easy to distinguish

71
this
  • this is a shortcut that can be used to refer to
    the current object
  • It is useful in event handlers to pass properties
    of the object to generic functions
  • This example passes the entire text object named
    month to the function checkrange()
  • ltinput type"text" name"month" size"2"
    onblur"checkrange(this, 1, 12) /gt

Otherwise would have to code something like
document.form1.month!
72
this Example
  • This function embedded in the ltheadgt tag
    processes the example on the previous page. Note
    that field can be any Javascript object which has
    a numeric value attribute
  • function checkrange (field, min_value, max_value)
  • if ((field.value lt min_value) (field.value gt
    max_value))
  • alert("The field value must be at least "
    min_value " and may not be greater than "
    max_value ".")
  • return false
  • else
  • return true

73
onabort Event
  • Action to occur when the user aborts loading an
    image
  • Occurs when the browser STOP button is pressed or
    clicks on an image before it is loaded
  • By default nothing happens which is out of the
    ordinary
  • Example
  • ltimg srcmyimage.gif onabortalert(User
    decided not to wait for image to load!) /gt

74
onblur Event
  • Occurs when the user leaves a form field (either
    by clicking outside the form field or pressing
    the tab key)
  • onblur and its cousin onchange are very popular
    for validating form fields
  • Example
  • ltinput typetext nameLastName size30
    onblurchecklength(this, 5, 30) /gt

75
onchange Event
  • Occurs when the value of a form field is changed
    by the user and loses focus, or when a new choice
    is made in a select element
  • Example
  • ltinput typetext namelastname size30
    onchangeconfirm(Are you SURE you want to
    change your last name?) /gt

76
onclick Event
  • Occurs when user clicks on a clickable form
    control or hyperlink with a mouse
  • Example
  • lta hrefhttp//www.yahoo.com onclickalert(You
    are about to go to Yahoo!)gtGo to Yahoo!lt/agt

77
onerror Event
  • Occurs when a document or image fails to load
    properly
  • Example
  • ltimg srcmyimage.gif onerroralert(The image
    is corrupt! Please notify the Webmaster!) /gt

78
onfocus Event
  • Occurs when a window or form field is made active
    by moving the cursor into the field or clicking
    on the object
  • Example
  • ltinput typetext namelastname size30
    onfocusalert(You have selected the field named
    this.name) /gt

79
onload Event
  • Action to take when the page has finished loading
  • onunload is similar and occurs when a document is
    unloaded
  • Example
  • ltbody onloadalert(The document has finished
    loading. You may begin working on this page
    now.) /gt

80
onmouseover Event
  • Occurs once each time the mouse pointer moves
    over an object or area from outside that object
    or area
  • Example
  • lta href"http//home.netscape.com/"   onmouseover
    "window.status'Click this if you
    dare!' return true"gt Click melt/agt

81
onmouseout Event
  • Occurs each time the mouse pointer leaves an area
    (client-side image map) or link from inside that
    area or link
  • Example
  • lta href"http//www.buy.com/"   onmouseout"windo
    w.statusYou missed a fabulous opportunity
    for savings! return true"gt Click melt/agt

82
onsubmit Event
  • Can be used to prevent a form from being
    submitted
  • Commonly used with a form validation logic
  • Must put the word return in front of your code.
    Anything other than a false value will let the
    form submit
  • A common mistake is to instead attach logic to
    the onClick event of a submit button. This wont
    keep the form from submitting!
  • Example
  • ltform namemyform" actionhttp//www.myurl.com/p
    rocessform" onsubmitreturn validate_form(this)
    gt

83
onreset Event
  • Occurs when a reset button on the form is pressed
  • Event only works in the form tag
  • A common mistake is to attach logic to the
    onclick event of a reset button. This wont keep
    the form from resetting!
  • Example
  • ltform name"form1" actionhttp//www.myurl.com/pr
    ocessform" onsubmitreturn validate_form(this)gt
    onreset"alert(Defaults have been
    restored.')gt

84
onselect Event
  • Occurs when a user selects some of the text
    within a text or textarea field
  • Example
  • ltinput type"text" value"" name"valuefield"
    onselectalert(onSelect event was
    triggered!) /gt

85
Object Event Handlers
  • Button - onclick
  • Check Box - onclick
  • Document - onload, onunload, onerror
  • Form - onsubmit, onreset
  • Frames - onblur, onfocus
  • Hyperlink - onclick, onmouseover, onmouseout
  • Image - onload, onerror, onabort

86
Object Event Handlers
  • Image Hot Spot - onmouseover, onmouseout
  • Input Box - onblur, onchange, onfocus, onselect
  • Radio Button - onclick
  • Reset Button - onclick
  • Selection List - onblur, onchange, onfocus
  • Submit Button - onclick
  • Text Area Box - onblur, onchange, onfocus,
    onselect
  • Window - onload, onunload, onblur, onfocus

87
Emulating Events
  • There are a number of methods for Javascript
    objects that let you pretend to be executing an
    event
  • click(), clear(), reset(), submit(), blur(),
    close(), focus() and select()
  • These can be useful, for example, to force the
    focus back into a particular field, use the
    focus() event
  • Use with care, particularly focus() events
    because they can cause loops that will hang your
    browser!

88
Warnings
  • JavaScript is a big, complex language
  • Weve only scratched the surface
  • Its easy to get started in JavaScript, but if
    you need to use it heavily, plan to invest time
    in learning it well
  • Write and test your programs a little bit at a
    time
  • JavaScript is not totally platform independent
  • Expect different browsers to behave differently
  • Write and test your programs a little bit at a
    time
  • Browsers arent designed to report errors
  • Dont expect to get any helpful error messages
  • Write and test your programs a little bit at a
    time

89
References
  • W3 Schools JavaScript Tutorial
  • http//www.w3schools.com/js/default.asp
  • Several Online Presentations
Write a Comment
User Comments (0)
About PowerShow.com