JavaScript csc667867 Spring 2006 Ilmi Yoon - PowerPoint PPT Presentation

1 / 109
About This Presentation
Title:

JavaScript csc667867 Spring 2006 Ilmi Yoon

Description:

1997 dHTML is born with Version 4.0 browsers. Web Programmers strike it rich. 6 ... DHTML. http://www.bart.gov. Browser Detection. Server-Side. 8. Dynamic HTML ... – PowerPoint PPT presentation

Number of Views:34
Avg rating:3.0/5.0
Slides: 110
Provided by: elli45
Category:

less

Transcript and Presenter's Notes

Title: JavaScript csc667867 Spring 2006 Ilmi Yoon


1
JavaScriptcsc667/867Spring 2006Ilmi Yoon
2
Outline
  • Basics of JavaScript, History
  • Basics of the language
  • variables, types, arrays, objects, and functions
  • operators, expressions, strings, and statements
  • Some simple examples
  • JavaScript Full Reference at http//wp.netscape.co
    m/eng/mozilla/3.0/handbook/javascript/

3
What is JavaScript
  • JavaScript is a simple, interpreted,
    programming language with elementary
    object-oriented capabilities
  • JavaScript has two distinct but overlapping
    systems
  • client-side JavaScript runs on Web browsers
  • server-side JavaScript runs on Web servers
  • Syntactically JavaScript resembles C, C, Java
  • JavaScript was developed by Netscape (formerly
    called LiveScript)

4
What JavaScript Programs Can Do
  • Write programs to perform any computation it is
    equivalent in power to a general purpose
    programming language
  • Control Web page appearance and content (this is
    its intended use)
  • Control the Web browser, open windows and frames
  • Interact with document content
  • Retrieve and manipulate all hyperlinks
  • Interact with the user
  • Read/write client state with cookies

5
Short History of JavaScript
  • Released in 1996 with Netscape 2
  • Originally called LiveScript
  • MS releases Jscript with IE 3.0
  • Unreliable and buggy
  • 1997 dHTML is born with Version 4.0 browsers. Web
    Programmers strike it rich.

6
Short History of JavaScript
  • 1999 begin to see versions of W3C Dom guidelines
    implemented in versions of JavaScript and Jscript
  • Netscape and Open Source Community drop old
    Netscape core to develop first browser to meet
    W3C DOM guidelines
  • Most new browsers now support W3C Dom

7
Common Uses of JavaScript
  • Client Side
  • Image Rollovers (most common)
  • Form Validationhttp//www.papiowines.com/contactu
    s.asp
  • Dynamic Form Generationhttp//www.robertmondavi.c
    om/Wheretobuy/
  • DHTMLhttp//www.bart.gov
  • Browser Detection
  • Server-Side

8
Dynamic HTML
  • An integration of JavaScript, Cascading Style
    Sheets, and the Document Object Model.
  • Most common type is drop down menus
  • Created by accessing an html elements style sheet
    and changing its visibility

9
What is DOM?
  • Document Object Model (DOM)
  • The Document Object Model is a platform- and
    language-neutral interface that will allow
    programs and scripts to dynamically access and
    update the content, structure and style of
    documents. from w3c.org

10
Debugging your script
  • Most common way
  • alert()
  • Better way
  • Use Firefox, Netscapetype javascript in the
    location bar and you will go to JavaScript
    console
  • Real Debugging
  • Go to Microsoft and download script debugger.
    User Beware.

11
Adding JavaScript to HTML
  • Inlineltscript languageJavaScriptgtlt!Hides
    script from old browsers Code goes
    here//?ltscriptgt
  • External Fileltscript languageJavaScript
    srcfile.js gtlt/scriptgt

12
JavaScript is Embedded in HTML
  • ltHTMLgt
  • ltHEADgt
  • lt/HEADgt
  • ltBODYgt
  • ltSCRIPT LANGUAGEJavaScriptgt
  • //the Javascript here produces content for the
    BODY on loading
  • lt/SCRIPTgt
  • lt/BODYgt
  • lt/HTMLgt
  • Deferred Script
  • ltHTMLgt
  • ltHEADgt
  • ltSCRIPT LANGUAGEJavaScriptgt
  • //the Javascript here creates functions for later
    use
  • lt/SCRIPTgt
  • lt/HEADgt
  • ltBODYgtlt/BODYgtlt/HTMLgt

13
JavaScript Object Hierarchy
  • self, window, parent, top
  • plugins
  • navigator
  • mimetypes
  • frames
  • location forms elements
  • Current
  • Window history anchors buttons
  • checkboxes
  • document links fileUpload
  • hidden
  • packages images password
  • radio
  • applets reset
  • select options
  • embeds submit
  • Java packages text
  • JavaClass objects textarea

14
JavaScript Built-in Objects and HTML Tags
  • Object HTML Tag Object HTML Tag
  • window N/A button ltINPUT TYPEbutton
  • frame ltFRAMEgt checkbox ltINPUT TYPEcheckbox
  • history N/A hidden ltINPUT TYPEhidden
  • location N/A passwordltINPUT TYPEpassword
  • document ltBODYgt radio ltINPUT TYPEradio
  • form ltFORMgt reset ltINPUT TYPEreset
  • select ltSELECTgt submit ltINPUT TYPEsubmit
  • textarea ltTEXTAREAgt text ltINPUT TYPEtext
  • link ltA HREFgt anchor ltA NAMEgt
  • navigator N/A

15
Key Objects
  • Document object is responsible for all content on
    a page contains all the user interface elements
    of a page
  • Window object represents a browser window or
    frame. This is the top-level object for each
    document,Location, and History object group.
  • Frame object
  • Location object
  • History object
  • Form objects can contain user interface elements
    for user input
  • Button objects include a button, submit and reset
    buttons

16
JavaScript - The Basics
  • JavaScript is case-sensitive
  • sum, SUM and Sum are 3 different identifiers
  • HTML is NOT case-sensitive
  • JavaScript ignores spaces, tabs, newlines
  • Semicolon is optional
  • but multiple statements on a line require a
    semicolon
  • i 1 j 2
  • C and C style comments are supported
  • //comment to end of line
  • / this can be a
  • multiple line comment /

17
JavaScript Literals
  • Literals
  • numbers, strings, true, false, null
  • All numbers are treated as floating point
  • base10 -(1-9)(0-9)
  • base8 -0(0-7)
  • base16 -0(xX)(0-9a-fA-F)
  • float (-)digits.digits(Ee)(-)digits
  • There are special numerical constants
  • Number.MAX_VALUE, Number.MIN_VALUE,
  • Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINIT
    Y

18
String Literals
  • Any sequence of zero or more characters enclosed
    within single or double quotes
  • Examples
  • a single quoted string
  • a double quoted string
  • alert(Please Click OK)

19
JavaScript Data Types
  • Type Example Description
  • String a string a series of characters inside
  • quote marks
  • Number 123.45 Any number not inside quote
    marks
  • Boolean true a logical true and false
  • Null null completely devoid of any value,
    not a number, not a string, different than
    0 in C/C
  • Object all properties and methods belonging
    to the object
  • Function a function

20
JavaScript Arrays and Objects
  • Arrays
  • one dimensional, indexed from zero
  • array elements can contain any type of data
    including references to other arrays, to objects,
    to functions
  • array elements can have different types
  • Objects
  • a collection of data where each item has a name
  • e.g. document has a property images array whose
    elements have properties width and height, e.g.
    document.imagesi.width

21
Arrays
  • Elements are normally accessed using
  • arr0 1
  • arrarr0 2
  • Arrays in JavaScript are sparse
  • arr0 1 arr10000 a string
  • only 2 indices are allocated
  • Arbitrary expressions are permitted in
  • framesij12
  • document.framesi.elementsj
  • Even expressions that evaluate to a string
  • documentlastModified

22
Array and Objects
  • Objects and arrays are really identical
  • typeof(array) typeof(object) object
  • typeof() returns a string which is the type of
    its argument (number, string, boolean,
    object, function, undefined)
  • Object elements are accessed using dot (.)
  • An object/array on the left requires a field name
    on the right of dot
  • document.lastModified
  • frames0.length
  • The dot operator can be used with arrays
  • arr1 is identical to arr.1
  • but if i 1, arr1 is not equivalent to arr.i
    since property names are not evaluated

23
Variables and Data Types
  • JavaScript is a loosely typed language
  • Data types are converted during execution as
    needed
  • Data typing only matters during operations
  • 6 67 667 String
  • 6 67 73

24
Variables and Data Types
  • Numbers
  • Integer and floating-point numbers.
  • Booleans
  • True or false. Can not use as 1 or 0 but 0
    false
  • Strings
  • Anything surrounded by or ex. My String
    My String
  • Object
  • myObj new Object()
  • Null
  • Not the same as zero - no value at all.
  • Undefined
  • The Variable has been created but no value has
    been assigned to it

25
Scope
  • Is the following code valid?for(var i 0 i lt
    10i) document.write(i)alert(i)

26
Scope
  • Is the following code valid?for(var i 0 i lt
    10i) document.write(i)alert(i)
  • YES! Scopes only happens within functions

27
Scope
  • var myInt 0 //Global Varfunction foo() var
    i 10 //local variable myInt
    idocument.write(i) //will cause error

28
Operators
  • Arithmetic (the usual suspects)
  • ,-,,/,,--,
  • Comparison
  • , !, gt, gt, lt, lt
  • Boolean
  • , , !

29
Statements
  • Conditionals
  • if(x lt 0) alert(x is negative)else alert(
    x is positive)
  • switch(favoriteProf) case Yoon
    statements break case Lank
    statements break default
    statement

30
Statements
  • Loops
  • for(var i 0 i lt myArray.lengthi) document.w
    rite(i)
  • do statements while (condition)
  • while(condition) statements

31
Functions
  • The function definition is a statement which
    describes the function its name, any values
    (known as "arguments") which it accepts incoming,
    and the statements of which the function is
    comprised.
  • function funcName(argument1,argument2,etc)
    statements

32
Functions
  • Examplefunction foo(myString) document.write(m
    yString)foo(Computers are fun)foo()
    //will this work?

33
Functions
  • When calling functions, JavaScript will try to
    match the function with same number of arguments
  • Previous example would work but the argument
    myString would be undefined.

34
JavaScript Objects
  • To declare an objectvar myObj new Object()
  • To set propertiesmyObj.name blah
  • Setting methods
  • myObj.foo foo

35
JavaScript Objects
  • Prototype an object function petDog(name,breed,ye
    ar) this.name name this.breed
    breed this.year yearvar myDog new
    petDog(rusty,mutt,1990)

36
Date Browser Output
37
Using alert(), confirm(), and prompt()
  • ltHTMLgtltHEADgtltTITLEgtExample of alert, confirm,
    promptlt/TITLEgt
  • ltSCRIPT LANGUAGEJavaScriptgt
  • function alertUser()
  • alert("An alert box contains an exclamation
    mark")
  • function confirmUser()
  • var msg "\n please confirm that you want\n"
  • "to test another button?"
  • if (confirm(msg))
  • document.write("lth2gtYou selected OKlt/h2gt")
  • else document.write("lth2gtYou selected
    Cancellt/h2gt")
  • function promptUser()
  • name1prompt("What is your name?, )
  • document.write("lth2gtwelcome to this page "
    name1 "lt/h2gt") lt/SCRIPTgtlt/HEADgt

38
Using alert(), confirm(), and prompt()
  • ltBODYgtwelcome to this pageltbrgt
  • ltFORMgt
  • ltINPUT TYPEbutton VALUE"Click here to test
    alert() onClick"alertUser()"gtltBRgt
  • ltINPUT TYPEbutton VALUE"Click here to test
    confirm()" onClick"confirmUser()"gtltBRgt
  • ltINPUT TYPEbutton VALUE"Click here to test
    prompt()" onClick"promptUser()"gtlt/FORMgtlt/BODYgtlt/H
    TMLgt

39
Clicking on alert()
40
Clicking on confirm()
41
Clicking on prompt()
42
Simple Examples
  • Swap Images
  • Steps
  • Preload images
  • On mouse over event swap the image
  • On mouse out event restore the image

43
Examples (continued)
  • Preload images
  • if(document.images) menu1img new
    Image() menu1img.src '/images/nav1_stations.gi
    f' menu1imgOn new Image() menu1imgOn.src
    '/images/nav1_stations_on.gif'
  • Swap Image function
  • function swapImage(imageName, newImage) if(docum
    ent.imagesimageName) document.imagesimageNam
    e.src newImage.src
  • The Html
  • lta href onmouseoverswapImage(menu1,menu1imgO
    n) onmouseoutswapImage(menu1,menu1img)gtltimg
    src/images/nav1_sations.gif idmenu1
    namemenu1 alt width130 height15
    /gtlt/agt

44
Form Validation
  • Create function to run on forms onSubmit event
  • ltform name"myForm" id"myForm" action""
    method"get" onsubmit"return checkForm(this)"gt
  • ltinput type"text" name"firstName"
    id"firstName" value"" /gt
  • ltinput type"submit" /gt
  • lt/formgt

45
Form Validation (continued)
  • function checkForm(theForm) if(theForm"firstNam
    e".value "") alert("You must enter your
    first name") theForm"firstName".focus()
    return false
  • return true

46
Other ways to access a form
  • document.forms0.elements0gets the first form
    and first element of the form
  • document.formsformName.elementselementName

47
Supporting IE and NS
  • IE and NS do not support the same JavaScript
    language
  • they include similar/identical capabilities, but
    the way to invoke them is different
  • We must write JavaScript that works across both
    browsers
  • if a client gets a JavaScript error it is
    annoying and there is nothing viewers can do

48
Multi-browser support
  • The JavaScript
  • /
  • Determine what code to use
  • /
  • if( document.all )
  • this.init IE_init
  • else if ( document.layers )
  • this.init NN_init
  • else if (document.getElementById)
  • this.init std_init

49
Multi-browser support (IE)
  • The JavaScript
  • /
  • Init functions
  • /
  • function IE_init()
  • this.SwapImageOn std_SwapImageOn
  • this.SwapImageOff std_SwapImageOff
  • this.TurnSubOn IE_TurnSubOn
  • this.TurnSubOff IE_TurnSubOff
  • this.TurnOffLevel2 std_TurnOffLevel2
  • this.TurnOnLevel2 std_TurnOnLevel2
  • __windowLoaded()

50
Multi-browser support
  • The JavaScript
  • function IE_TurnSubOn(sectionname)
  • if(eval(sectionname"SubDiv"))
  • if(active_sub_div)
  • TurnSubOff(active_sub_div)
  • active_sub_div sectionname
  • eval(sectionname"SubDiv").style.visibility
    "visible"
  • function NN_TurnSubOn(sectionname)
  • if(eval(sectionname"SubDiv"))
  • if(active_sub_div)
  • TurnSubOff(active_sub_div)
  • active_sub_div sectionname
  • document.layerssectionname"SubDiv".visibility
    "visible"

51
Multi-browser support
  • Browser Detection
  • function getBrowserSpecs()
  • var is new Object()
  • var agt navigator.userAgent.toLowerCase().toLow
    erCase()
  • // BROWSER VERSION
  • // Note On IE5, these return 4, so use is.ie5up
    to detect IE5.
  • var reNumber new RegExp( "0-9\." ) //
    assume the version is the first number in the
    USER AGENT
  • is.major parseInt( reNumber.exec( agt )0 )
  • is.minor parseFloat( reNumber.exec( agt )0
    )

52
A Simple Example
  • ltHTMLgt
  • ltHEADgt
  • ltTITLEgtSimple Javascriptlt/TITLEgt
  • lt/HEADgt
  • ltBODYgt
  • ltH1gtFirst Example of JavaScriptlt/H1gt
  • ltSCRIPT LANGUAGEJavaScriptgt
  • lt!-- hide from old browsers by embedding in a
    comment
  • document.write(Last updated on
    document.lastModified
  • .)
  • // end script hiding --gt
  • lt/SCRIPTgt
  • lt/BODYgt
  • lt/HTMLgt

53
Example 1 Browser Output
54
Another Example
  • ltHTMLgt
  • ltHEADgtltTITLEgtComputing Factorialslt/TITLEgtlt/HEADgt
  • ltBODYgt
  • ltH1gtAnother Example of JavaScriptlt/H1gt
  • ltSCRIPT LANGUAGEJavaScriptgt
  • document.write(ltH1gtFactorial Tablelt/H1gt)
  • for ( i 1, fact 1 i lt 10 i, fact fact
    i)
  • document.write(i ! fact)
  • document.write(ltBRgt)
  • lt/SCRIPTgt
  • lt/BODYgt
  • lt/HTMLgt

55
Another Example
56
JavaScript has Event Handlers
  • ltHTMLgt
  • ltHEADgtltTITLEgtHandling Events Examplelt/TITLEgtlt/HEAD
    gt
  • ltBODYgt
  • ltH1gtHandling Events in JavaScriptlt/H1gt
  • ltFORMgt
  • ltINPUT TYPEbutton VALUEClick me
  • onClickalert(You clicked me) gt
  • lt/FORMgt
  • lt/BODYgt
  • lt/HTMLgt

57
Example 3
58
Determining the Browser
  • navigator is a built-in object with properties
    that describe the browser
  • defined in both IE and NS
  • navigator.appName is a string with the browser
    name
  • navigator.appVersion is a string with the version
    number
  • to determine the correct version you may need to
    convert from string to number
  • parseFloat returns a number from a string, and
    ignores any part of the string after the number
  • Number only converts a string that is a number to
    a number

59
Determining the Browser
  • ltHTMLgtltHEADgtltTITLEgtCheck Browserlt/TITLEgt
  • lt/HEADgtltBODYgt
  • ltSCRIPT languageJavaScriptgt
  • document.write(ltBRgt This browser is
  • navigator.appName)
  • document.write(ltBRgt Version
  • navigator.appVersion)
  • if (parseFloat(navigator.appVersion) gt 4)
  • document.write(ltBRgt You have an up-to-date
  • browser)
  • lt/SCRIPTgt
  • lt/BODYgt
  • lt/HTMLgt

60
Browser Output
61
Avoiding Errors
  • Since IE and NS differ somewhat in JavaScript, it
    is useful to first check if an object, property
    or method exists
  • One can refer to any name in a conditional and if
    it is undefined the conditional returns false
  • newItem something//produces an error if
  • //something is undefined
  • if ( something ) newItem something
  • does not produce an error, but only changes
    newItem if something exists

62
Example Checking Window Size
  • NS and IE use different object properties to hold
    the window size
  • IE document.body.clientwidth or clientheight
  • NS window.innerWidth or innerHeight
  • Suppose you want to vary the response depending
    upon the size of the browser window
  • lets write a program that does this

63
Re-Direct the Browser
  • ltHTMLgtltHEADgtltTITLEgtre-direct based upon window
    sizelt/TITLEgtlt/HEADgt
  • ltBODYgtltSCRIPT languageJavaScriptgt
  • function windowHeight( )
  • if (document.body //test for IE
    document.body.clientHeight)
  • return document.body.clientHeight
  • else if (window.innerHeight) //test for NS
  • return window.innerHeight
  • else return 0 //both tests have failed
  • if (windowHeight() gt 500)
  • document.location fancy.html
  • else document.location lessfancy.html
  • lt/SCRIPTgtlt/BODYgtlt/HTMLgt

64
Points to Observe
  • If the check for IE and NS both fail then a
    height of 0 is returned and the lessfancy file is
    displayed
  • The conditional with the clause is checked
    left-to-right in short-circuit mode

65
Example A Dynamically Changing Banner
  • Use JavaScript to have a region where the HTML is
    dynamic
  • use the STYLE attribute to create an HTML block
    that is accessed by JavaScript
  • use a periodically scheduled event
  • id setInterval(JSstring, msec)
  • JSstring is JavaScript code and msec is
    milliseconds
  • JSstring is called every time

66
Browser Output
67
HEAD of the banner Example
  • ltHTMLgtltHEADltTITLEgtchanging bannerlt/TITLEgt
  • ltSCRIPT languageJavaScriptgt
  • var banners new Array()
  • banners0 banner0
  • banners1 banner1
  • banners2 banner2
  • var which 0
  • function update()
  • display(banner, bannerswhich)
  • which
  • if (which banners.length) which 0
  • display function
  • lt/SCRIPTgtltBODYgt...

68
What Document HEAD does
  • Defines array banners of HTML to display
  • Defines counter, called which, that tells which
    element is being displayed
  • Defines update which calls display() with ID
    banner and the current element of banners, then
    increments which

69
Changing HTML in a Region
  • function display(id, str)
  • if (document.all)
  • document.allid.innerHTMLstr
  • else
  • documentid.document.open()
  • documentid.document.write(str)
  • documentid.document.close()

70
BODY of Banner Example
  • ltHEADgtltTITLEgtVarying a Bannerlt/TITLEgt
  • ltSCRIPT LanguageJavaScriptgt
  • function update()/load new banner for
    eachcall/
  • lt/SCRIPTgtlt/HEADgt
  • ltBODY onload "if (setInterval)
    setInterval('update()', 5000)"gt
  • ltpgtAn example of a changing text bannerlt/Pgt
  • ltPgtltSPAN ID"banner" STYLE"positionabsolute"gtltI
    gt
  • ltSCRIPT LanguageJavascriptgt
  • if (setInterval)
  • document.write('the banner is loading')
  • else document.write('Get a new browser')
  • lt/SCRIPTgtlt/Igtlt/SPANgt
  • ltBRgtltPgtHere is the remainder of the documentlt/Pgt
  • lt/BODYgtlt/HTMLgt

71
Points to Observe
  • Uses onload event handler to start a periodic
    event with setInterval
  • runs the function update() every 5 seconds
  • update must be defined in the HEAD
  • does nothing if setInterval is not defined
  • Uses an HTML SPAN tag to define the element that
    the update function will change
  • has an ID (similar to a name, but for all tags
    and is unique in the document)
  • has a STYLE attribute specifying absolute
    position
  • needed in NS to modify the region

72
Something on STYLE
  • When an HTML tag specifies a style, the position
    of the element can be controlled
  • very useful for layout
  • for NS to change the text, the position must be
    absolute
  • this creates some awkwardness
  • the next element is relative, and it turns out
    this means it will overlap the SPAN region that
    is being changed
  • fix this using some BR tags to skip ahead

73
Changing the SPAN region
  • NS and IE uses different ways to alter what is in
    an HTML region
  • IE has innerHTML property which when set to a new
    value displays that HTML in the region
  • document.allid.innerHTML str
  • NS has a document object for each such region
  • open this document, write to it, and then close
    it
  • documentid.document.open()
  • documentid.document.write(str)
  • documentid.document.close()

74
About display()
  • Checks to see if document.all is defined
  • if so, uses IE4 convention of changing innerHTML
  • Otherwise assumes NS and uses NS conventions
  • note, this function will not be called for older
    browsers, because setInterval is not defined so
    the onload method does nothing

75
Accessing the SPAN Region
  • A SPAN tag with an ID attribute creates a
    JavaScript variable that can be used to modify
    that region of the document
  • array of objects, one for each HTML tag, with an
    ID attribute
  • accessed using the ID - string with a name
  • slightly different in NS and IE
  • document.allid in IE
  • documentid in NS
  • e.g. document.allbanner or documentbanner

76
Highlighting Menus
  • Menus whose elements are temporarily highlighted
    as the mouse moves over them
  • One way use two images for each menu item and
    change between them using the mouseover and
    mouseout events
  • this works in NS and IE version 4 or later
  • Second way use STYLE attributes to dynamically
    change color, but this is harder to get working
    on both browsers

77
Image Object
  • Each image in an HTML document has an associated
    JavaScript object
  • the properties of the object include
  • width and height in pixels
  • src, URL of the image file, changes image when
    set
  • complete, true after images finishes loading
  • can refer to object by NAME attribute of HTML IMG
    tag, or via built-in array of images
  • document.images.name
  • document.imagesindex where index is either a
    number or a string containing the name of the
    image

78
More on Image Object
  • An image object is created automatically for each
    IMG tag in a document
  • if there is no name attribute, then one cannot
    refer to it by name in JavaScript
  • An image object can also be created in JavaScript
  • var myImage new Image()
  • this can be used to load images into a document
    that are not visible in the displayed document
  • pre-fetching to make images appear immediately

79
An Image Rollover
  • Image rollover is the effect used to change
    between two images when the mouse moves over it
  • the images must be the same size
  • for the changes to be immediate, images must be
    pre-fetched
  • Generally used in highlighting menus, can be used
    wherever you want an image to change when the
    mouse moves over it
  • try http//www.ruleweb.com/dhtml/index.html

80
Rollover Example
  • ltHTMLgtltHEADgtltTITLEgtImage rolloverlt/TITLEgt
  • ltSCRIPT languagejavascriptgt
  • function highlightdocs()
  • if (document.images)
  • document.imagesdocs.src docsOn.src
  • function unhighlightdocs()
  • if (document.images)
  • document.imagesdocs.src docsOff.src
  • if (document.images)
  • docsOn new Image()
  • docsOn.src images/docs_on.gif
  • docsOff new Image()
  • docsOff.src images/docs_off.gif
  • lt/SCRIPTgtlt/HEADgtltBODYgtltPgt
  • ltA HREFdocuments.html onMouseOverhighlightdoc
    s() onMouseOutunhighlightdocs()gt
  • ltIMG SRCimages/docs_off.gif height25 width25
    namedocs border0 altdocumentsgtlt/Agtlt/Pgtlt/BODYgtlt/
    HTMLgt

81
Observe in the BODY
  • The BODY creates an anchor with an image inside
  • there are mouse event handlers
  • image tag sets height, width, no border, alt text
    and name
  • the name is used to refer to the image in
    javaScript, document.imagesdocs
  • the HEAD defines two functions
  • only runs if browser supports image object
  • changes image by setting its src property to that
    of another, pre-fetched image called docs_on.gif

82
More on the HEAD
  • Highlighting requires two images
  • the image is created, then set is src property
    which loads the image
  • the names docsOn and docsOff are only used inside
    the functions, so it is OK to define them after
  • not used until the event handlers are activated
    by the mouse moving over the image

83
Generalizing to Multiple Images
  • Suppose we want a general highlight/unhighlight
    functions for any image in a document
  • define two arrays onImages and offImages
  • store pre-fetched images in these arrays,
    according to the same name as used for the image
    in the HTML
  • in general arrays can be indexed by strings as
    well as numbers

84
Pre-fetching Required Images
  • If (document.images)
  • var onImages new Array
  • var offimages new Array
  • onImagesdocs new Image()
  • onImagesdocs.src images/docs_on.gif
  • offImagesdocs new Image()
  • offImagesdocs.src images/docs_off.gif
  • onImagestech new Image()
  • onImagestech.src images/tech_on.gif
  • offImagestech new Image()
  • offImagestech.src images/tech_off.gif

85
General Highlighting Functions
  • Name each image in the HTML document with the
    same name used in the pre-fetch arrays, onImages
    and offImages
  • e.g. the name docs was used for the images, so
    use the same name in the HTML
  • then one can highlight by simply setting the src
    property of an element in document.images to the
    src property of that element in onImages
  • ltIMG SRCimages/docs_off.gif height25 width25
    namedocs border0 altdocumentsgt

86
Code for General Highlighting
  • function highlight(imgName)
  • if (document.images)
  • document.imagesimgName.src
  • onImagesimgName.src
  • function unhighlight(imgName)
  • if (document.images)
  • document.imagesimgName.src
  • offImagesimgName.src

87
Summary
  • How to write JavaScript that works across
    browsers
  • checking that the browser supports a given
    feature such as document.images, before using it
  • avoid annoying JavaScript errors that occur when
    viewing in one browser or the other
  • the built-in image object in JavaScript
  • accessing via name or array of images
  • created automatically for each IMG tag in the
    HTML
  • can also be created using new Image() in
    JavaScript

88
But Pre-fetching Repeats Code
  • Each image to be highlighted requires creating
    two images and setting their src properties
  • Repeated code is an indication of where to use
    subroutines
  • Alternate strategy create a global array with
    the names of all the images that will be used
  • must be the same as the names in IMG tags
  • this code requires images stored on the server to
    have file names based on these names
  • specify a path and extension
  • path name _on. ext(noteappends)
  • so path images/, namedocs, extgif then
    file must be in relative location
    images/docs_on.gif
  • loop over the elements in this name array,
    creating and loading the images

89
Pre-Fetching Function
  • function prefetch(path, extension)
  • var imageName, i
  • if (document.images)
  • for ( i 0 i lt imageNames.length i)
  • imageName imageNamesi
  • onImagesimageName new Image()
  • onImagesimageName.src path imageName
    _on. extension
  • offImagesimageName new Image()
  • offImagesimageName.src path imageName
    _off. extension

90
Remainder of set-up
  • var imageNames new Array(docs, tech,
    banner1, banner2)
  • if (document.images)
  • var onImages new Array()
  • var offImages new Array()
  • prefetch(images/, gif)
  • There are four highlighting images in array

91
Body of Four Images
  • ltBODYgt
  • ltPgtltA HREFdocuments.html onMouseOverhighlight(
    docs) onMouseOutunhighlight(docs)gt
  • ltimg srcimages/docs_off.gif namedocs border0
    altdocuments width25 height25gtlt/AgtltBRgt
  • ltA HREFtechnology.html onMouseOverhighlight(
    tech) onMouseOutunhighlight(tech)gt
  • ltimg srcimages/tech_off.gif nametech border0
    alttechnology width25 height25gtlt/AgtltBRgt
  • ltA HREFmembers.html onMouseOverhighlight(bann
    er1) onMouseOutunhighlight(banner1)gt
  • ltimg srcimages/banner1_off.gif namebanner1
    border0 altbanner1 width25 height25gtlt/AgtltBRgt
  • . . . But there is still lots of repeated HTML

92
Reducing Repeated Code
  • Use document.write to produce the required HTML
  • document.write(ltA HREF hrefsI
    onmouseoverhighlight(\ imageName \)
    onmouseoutunhighlight(\ imageName
    \)gt
  • ltIMG src path imageName _off.
    extension name imageName
    border0 alt altTextI
    width w height h gtlt/Agtlt/BRgt

93
Some Explanations
  • Consider
  • document.write(ltA HREF hrefsi )
  • which produces the HTML
  • ltA HREFdocuments.html
  • Consider
  • document.write(onmouseoverhighlight(\
    imageName \)
  • which produces the HTML
  • onmouseoverhighlight(docs)
  • where imageName has value docs

94
Function for Creating the Menu
  • Function createHighlightMenu(path, extension, w,
    h)
  • var imageName, I
  • for (i0 i ltimagesNames.length i)
  • imageNameimageNamesi
  • if (document.images)
  • onImagesimageName new Image()
  • onImagesimageName.src path imageName
  • _on. extension
  • offImagesimageName new Image()
  • offImagesimageName.src path imageName
  • _off. extension
  • document.write(ltA HREF hrefsi
    onmouseoverhighlight(\imageName \)
    onmouseoutunhighlight(\ imageName
    \)gtltIMG src path imageName _off.
    extension nameimageName border0
    alt altTexti width w
    height h gtlt/AgtltBRgt)

95
Document Body Using this function
  • ltBODYgtltPgtltSCRIPT languageJavaScriptgt
  • var imageNames new Array(docs, tech,
    banner1, banner2)
  • var hrefs new Array(document.html,
    tech.html, banner1.html, banner2.html)
  • var altText new Array(Docs, Techs, banner1,
    banner2)
  • if (document.images)
  • var onImages new Array()
  • var offImages new Array()
  • createHighlightMenu(images/, gif, 25, 25)
  • lt/SCRIPTgtlt/Pgtlt/BODYgtlt/HTMLgt

96
Example Document Object Property Values
  • Property Value
  • document.title My Home Page"
  • document.fgColor 000000
  • document.bgColor ffffff
  • location.href "http//www.usc.edu/in.html
    "
  • history.length 8

97
window.open() Method Attribute Examples
  • To create a new window that shows only the
    toolbar and status bar and is resizable
  • window.open(newURL, New Window,
    toolbar,status,resizable)
  • the height and width defaults are the same as the
    browser
  • a new window is positioned in the upper left hand
    corner of the screen
  • a call to window.open() returns a value of the
    new windows object this should always be
    assigned to a variable, e.g.
  • newWindow window.open(,)
  • if (newWindow ! null)
  • newWindow.document.write(ltHTMLgtltHEADgtltTITLEgtHilt/
    TITLEgtlt/HEADgt)

98
Example
  • ltHTMLgtltHEADgtltTITLEgtPutting Up a Help
    Windowlt/TITLEgt
  • ltSCRIPT LANGUAGEJavaScriptgt
  • function displayHelp()
  • hWin window.open(, Help,
    height200,width400)
  • hWin.document.write(ltBODYgtA Sample Help
    WindowltBRgt)
  • hWin.document.write(Please provide your first
    and last nameltBRgt)
  • hWin.document.write(Your Phone number should
    have no hyphens)
  • hWin.document.write(ltFORMgtltINPUT TYPEbutton
    valueOK onClickwindow.close() gt)
  • hWin.document.write(lt/FORMgtlt/BODYgt)
  • lt/SCRIPTgtlt/HEADgtltBODYgt
  • ltFORM NAMEmyform methodPOSTgtltH2gtHere is my
    Formlt/H2gt
  • NAME ltINPUT TYPEtext namenamegtltBRgt
  • Address ltINPUT TYPEtext nameaddressgtltBRgt
  • Phone ltINPUT TYPEtext namephonegtltBRgt
  • ltINPUT TYPEsubmit VALUEClick Heregt
  • ltINPUT TYPEbutton VALUEHelp
    onClickdisplayHelp()gt
  • lt/FORMgtlt/BODYgtlt/HTMLgt

99
Help Window Browser Output
100
Example Checking for Empty Fields
  • ltHTMLgtltHEADgtltTITLEgtElements Arraylt/TITLEgt
  • ltSCRIPT LANGUAGE"javaScript"gt
  • function doit()
  • for (i 0 i lt 3 i)
  • if (document.forms0.elementsi.value "")
  • alert("Please fill out all fields.")
  • document.forms0.elementsi.focus()
  • break
  • lt/SCRIPTgtlt/HEADgtltBODYgt ltFORM METHOD"POST"gt
  • Enter your first name ltINPUT TYPE"text"
    NAME"firstname"gtltPgt
  • Enter your last name ltINPUT TYPE"text
    NAME"lastname"gtltPgt
  • ltINPUT TYPE"radio" NAME"gender"gtMale
  • ltINPUT TYPE"radio" NAME"gender"gtFemaleltPgt
  • ltINPUT TYPE"checkbox" NAME"retired"gtI am
    retiredltbrgt
  • ltINPUT TYPE"button" NAME"act" VALUE"Verify
    onClick"doit()"gt
  • lt/FORMgtlt/BODYgtlt/HTMLgt

101
Checking for Empty Fields Browser Output
102
  • ltHTMLgtltHEADgtltTITLEgtChecking Elements in a
    Formlt/TITLEgt
  • ltSCRIPT LANGUAGEJavaScriptgt
  • function checkFields()
  • var size document.myform.elements.length
  • var Flag true
  • for (var i 0 i lt size i)
  • if ((document.myform.elementi.value null
  • document.myform.elementi.value )
  • (typeof document.myform.elementi.value !
    submit
  • typeof document.myform.elementi.value !
    reset)
  • Flagtrue alert(The document.myform.elem
    entsi.name field is blank. Please enter a
    value.) break //endif
  • //end of for
  • return Flag
  • lt/SCRIPTgtlt/HEADgtltBODYgt

103
  • ltFORM NAMEmyform methodPOST
    onSubmitreturn checkFields()gt
  • ltH2gtHere is my Formlt/H2gt
  • Name ltINPUT TYPEtext namenamegtltBRgt
  • Address ltINPUT TYPEtext nameaddressgtlt BRgt
  • Phone ltINPUT TYPEtext namephonegtlt BRgt
  • ltINPUT TYPEsubmit VALUEClick Heregtlt BRgt
  • lt/FORMgtlt/BODYgtlt/HTMLgt

104
Browser Output
105
Multiple Selection Example
  • ltHTMLgtltHEADgtltTITLEgtUsing Multiple Selection
    Listslt/TITLEgt
  • ltSCRIPT LANGUAGE"JavaScript"gt
  • function displaySelectionValues(objectName) var
    ans ""
  • for (var i 0 i lt objectName.length i)
  • if(objectName.optionsi.selected)
  • ans objectName.optionsi.text "ltBRgt"
  • myWin window.open("", "Selections",
    "height200,width400")
  • myWin.document.write("you picked these
    teamsltBRgt")
  • myWin.document.write(ans)
  • lt/SCRIPTgtlt/HEADgtltBODYgt
  • ltFORM NAME"myform" method"POST"gt
  • ltSELECT NAME"teams" size3 multiplegt
  • ltOPTION value"dodgers"gtDodgersltOPTION
    value"yankees"gtYankees
  • ltOPTION value"angels"gtAngels lt/SELECTgtltBRgt
  • ltINPUT TYPE"button" value"Show Selected Items"
  • onClick"displaySelectionValues(this.form.teams)"gt
  • lt/FORMgtlt/BODYgtlt/HTMLgt

106
Multiple Selection Lists Browser Output
107
Working with the Date Object
  • getDate() returns date within month (1-31)
  • getDay() returns day within week (0-6)
  • getHours() returns hour within day (0-23)
  • getMinutes() returns minutes within hour (0-59)
  • getMonth() returns month within year (0-11)
  • getSeconds() getTime()
  • getYear() getTimeZoneOffSet()
  • setDate(arg) sets date within month (1-31)
  • setHours(arg) sets hour within day (0-23)
  • setMinutes(arg)sets minutes within hour (0-59)
  • setMonth(arg) sets month within year (0-11)
  • setSeconds() setTime() setYear()

Objects have get and set functions
108
  • ltHTMLgtltHEADgtltTITLEgtUsing the Date Object
    lt/TITLEgtlt/HEADgt
  • ltBODYgt
  • The Date object has methods getMonth(),
    getDay(), getYear()ltbrgt
  • ltSCRIPT LANGUAGEJavaScriptgt
  • update new Date(document.lastModified)
  • theMonth update.getMonth() 1
  • theDay update.getDay()
  • the Year update.getYear()
  • document.writeln(ltIgtLast updated theMonth
    / theDay / theYear lt/Igt)
  • lt/SCRIPTgt
  • lt/BODYgtlt/HTMLgt

109
Date Object Browser Output
Write a Comment
User Comments (0)
About PowerShow.com