javascript browser

Upload: snehavenky

Post on 02-Jun-2018

231 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/10/2019 JavaScript Browser

    1/26

    2009 Marty Hall

    JavaScript:A Crash Course

    Part II: Browser-S ecific Features

    Originals of Slides and Source Code for Examples:

    -

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    . . .

    2009 Marty Hall

    For live Ajax & GWT training, see trainingcourses a p: courses.coreserv e s.com .Taught by the author of Core Servlets and JSP, More

    , .venues, or customized versions can be held on-site at

    your organization.

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    ourses eve ope an aug y ar y a Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF 1.x& 2.0, Ajax, GWT, custom mix of topics

    Ajax courses can concentrate on one library (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo) or survey several

    Courses developed and taught by coreservlets.com experts (edited by Marty) Spring, Hibernate/JPA, EJB3, Ruby/Rails

    Contact [email protected] for details

  • 8/10/2019 JavaScript Browser

    2/26

    Topics in This Section

    XMLGetting document

    Ajax

    From string (for interactive testing)

    Document, Element, and Node classes

    HTMLHTMLDocument and HTMLElement classes

    The Window class

    General event-handling attributes

    Element-specific event-handling attributes5

    2009 Marty Hall

    Intro

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

  • 8/10/2019 JavaScript Browser

    3/26

    Browser-Specific Classes

    Previous lectureDescribed core JavaScript syntax and objects

    This lecture escr es ava cr pt spec ca y or rowser app cat ons

    Reminder re references

    http://www.w3schools.com/js/

    http://www.w3schools.com/htmldom/dom_reference.asp

    http://www.devguru.com/technologies/ecmascript/QuickRef/javascript_intro.html

    Book JavaScript, the Definitive Guide by David Flanagan

    7

    2009 Marty Hall

    XML

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

  • 8/10/2019 JavaScript Browser

    4/26

    Overview

    API is very similar to Java DOM API you now ava org.w c. om c asses an met o s, t ey

    are almost the same in JavaScript Document classRepresents top-level document

    Also a specialized version representing the HTML page

    Represents XML/HTML element Inherits Node methods plus has some extras

    Node class

    Represents node in XML tree , ,CDATA notes, and a few others

    Most Element methods inherited from here9

    Getting Document: Real Life

    Getting general XML documentYou get XML document as the result of an Ajax request

    var xmlDocument = request.responseXML;

    page

    " "Many special features apply

    getDocumentById method, innerHTML property fore emen s, orms an anc ors an mages proper es,case-insensitivity for getElementsByTagName, lots morespecific to HTML

    . .dom_obj_document.asp

    10

  • 8/10/2019 JavaScript Browser

    5/26

    Getting Document:

    Firefoxvar xm r ng = a ... a ;var parser = new DOMParser();

    var xmlDocument =parser.parseFromString(xmlString, "application/xml");

    Internet Explorervar xmlDocument =new ActiveXObject("Microsoft.XMLDOM");

    xmlDocument.asynch = false;xmlDocument.loadXML(xmlString);return(xmlDocument);

    Check if (typeOf DOMParser != "undefined")

    True: use Firefox approach

    Warning: just for practice

    11

    Syntax Summary

    Document class ropert es

    documentElement

    Methods getElementById (HTML only), getElementsByTagName

    Element class

    getAttribute, getElementsByTagName, hasAttribute

    NodePropert es

    attributes, childNodes, firstChild, lastChild, nextSibling,nodeName, nodeType, nodeValue, parentNode,

    Methods hasAttributes, hasChildNodes, normalize

    12

  • 8/10/2019 JavaScript Browser

    6/26

    The Document Class

    documentElement property T e root E ement o t e ocument

    getElementById method Returns the Element with the specified ID.

    For HTML documents only!

    Refers to attribute that the DTD defines as an id attribute, not necessarilynamed id. Does not match attributes named id in regular XML docs.

    s suppose o e case-sens ve, u s case- nsens ve

    getElementsByTagName Returns an array of Elements that have that tag name

    Can use * for all Elements in document

    Unsupported in IE 5

    Is case-sensitive for regular XML documents

    Is case-insensitive for HTML documents

    Even when using XHTML

    13

    The Document Class: Examples

    function getXmlDoc(xmlString) {var arser = new DOMParservar xmlDocument =parser.parseFromString(xmlString, "application/xml");return(xmlDocument);

    }var test ="" +" ' ' ""Rafael" +"Nadal" +

    "" +"" +"Roger" +"Federer" +

    "< customer>" +"";

    var testDoc = getXmlDoc(test);14

  • 8/10/2019 JavaScript Browser

    7/26

    The Document Class: Examples

    15

    The Element Class

    getAttributeGets value of designated attribute.

    E.g., if element refers to ...," " " ".

    getElementsByTagName

    Returns an arra of subelements that have this ta nameSubelements can be arbitrarily nested

    hasAttributeTests if element has attribute of given name

    Also inherits from Node classSee next slides

    All Elements are Nodes, but not vice versa16

  • 8/10/2019 JavaScript Browser

    8/26

    The Node Class: Properties

    attributes

    childNodes An array of direct child nodes. 0-length if no children.

    , , Specific child nodes. Parent node (null for top element).

    nextSibling, previousSibling

    nodeName For Element nodes, the XML element name

    Node.ELEMENT_NODE, Node.TEXT_NODE,

    Node.ATTRIBUTE_NODE, Node.CDATA_SECTION_NODE,and a few other options. Fails on some IE versions!

    nodeValue For Text nodes, the body content. Call normalize first. See next slide.17

    Fixing Node Types in Internet

    ProblemOfficial standards Node.TEXT_NODE etc., unsupported

    through Internet Explorer 6 (OK in IE 7)

    Redefine them

    http://www.ibm.com/developerworks/xml/library/x-matters41.html

    if (!window['Node']) {window.Node = new Object();Node.ELEMENT_NODE = 1;Node.ATTRIBUTE_NODE = 2;Node.TEXT_NODE = 3;

    o e. _ _ = ;Node.DOCUMENT_NODE = 9; }

    18

  • 8/10/2019 JavaScript Browser

    9/26

    The Node Class: Methods

    hasAttributesDoes this Node have any attributes at all?

    hasChildNodes oes t s o e ave any c ren at a

    normalize .

    Important if element has body content that spans multiplelines or has extra white space.

    u you can s ave emp y ex no es

    You can call it on root element just once. xmlDoc.documentElement.normalize();

    19

    Node and Element: Examplefunction showInfo(node, indent) {if (node.nodeType == Node.TEXT_NODE) {conso e. og " s Bo y content s ' s'.",

    spaces(indent), node.nodeValue);} else if (node.nodeType == Node.ELEMENT_NODE) {console.log("%s Found element '%s'.",

    , .var children = node.childNodes;for(var i=0; i

  • 8/10/2019 JavaScript Browser

    10/26

    2009 Marty Hall

    Capabilities

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    HTMLDocument: Properties

    Obtain with predefined 'document' variable pec a ze su c ass o ocument c ass scusse ear er

    Properties , ,

    Info about the document. URL is same aswindow.location.href unless redirection occurs

    bod The body element

    anchors, applets, forms, images, links ,

    document. Usually better to find elements by ids.

    cookie, lastModified, referrer ,

    blah Element that has name="blah" (first one if repeated)

    22

  • 8/10/2019 JavaScript Browser

    11/26

    HTMLDocument: Methods

    write, writeln ynam ca y nsert text nto ocument

    Used from tag that has body contentNot used b A ax res onse handlers

    Use HTMLElement.innerHTML property instead

    getElementsByName

    getElementsByTagNameReturns arra of elements that have iven element name

    Case insensitive Inherited from Document class (see earlier slide)

    Finds element with specified id attribute

    Inherited from Document class (see earlier slide)23

    HTMLElement Subclass of Element class. Obtain with

    document.body, document.getElementsByTagName,document.getElementsByName, document.images. etc.

    otherElement.getElementsByTagName, otherElement.childNodes,otherElement.firstChild, etc.

    Most important properties id

    The id attribute nodeName

    Element name (inherited from Node class). name

    The name attribute (for HTML elements with "name" only) innerHTML

    Read/write property giving HTML text inside element style

    CSS2Properties object representing element styling className

    Space-separated list of CSS class names Method

    scrollIntoView Scrolls browser so element is visible

    24

  • 8/10/2019 JavaScript Browser

    12/26

    Form Class

    Obtaining referencedocument.forms array, form variable for code invoked

    by input element

    (getElementById, childNodes, etc.)

    Properties elements

    Array of all input elements in form

    , , , , Corresponds to HTML attributes

    Methods submit, reset

    25

    Image Class

    Obtaining reference ocument. mages array, ocument.name mage

    Any method or property that returns Node(getElementById, childNodes, etc.)

    Properties src

    . . Preload images first with new Image(...) and setting its

    href, so browser will have images cached.

    , , , , , , , ,vspace, width

    Corresponds to HTML attributes

    Node, Element, HTMLElement

    26

  • 8/10/2019 JavaScript Browser

    13/26

    Input Class

    Obtaining reference t e orm.e ements array

    Any method or property that returns Node(getElementById, childNodes, etc.)

    Propertiesname, id, value, type, disabled, form (enclosing form)

    defaultValue Initial value as given in the HTML

    ype-spec c proper es see on ne checked, maxLength, useMap, etc.

    Methodsblur/focus (all), click (buttons, checkboxes, radio

    buttons), select (file, password, text)27

    Window Class: Properties

    Obtaining referenceUse window or self

    history story o ect. ot wr ta e.

    location .

    location.href = "new address" redirects browser

    Status line value. Writable.

    Size/ osition/scrollin innerWidth, innerHeight, outerWidth, outerHeight,

    screenX (or screenLeft), screenY (or screenTop)28

  • 8/10/2019 JavaScript Browser

    14/26

    Window Class: Methods

    alert, confirm, promptPops up dialog boxes of various sorts

    print nvo es pr nt a og

    setInterval, clearInterval [repeated actions] ,

    setTimeout, clearTimeout [one-time actions] ,

    getComputedStyleGet st le info for s ecified element

    MovementLots of methods for opening, closing, resizing windows

    29

    2009 Marty Hall

    Event Handling

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

  • 8/10/2019 JavaScript Browser

    15/26

  • 8/10/2019 JavaScript Browser

    16/26

    Pros and Cons of Event-

    Assigning to property directly in HTML

    Simpler, especially for beginners

    Assigning to property indirectly someElement.onclick = someFunctionName;

    This approach is sometimes known as unobtrusiveJavaScript.

    Better se aration: all JavaScri t in JS files. HTML filecontains only HTML.

    More work to set up unless you use a JavaScript librarylike Prototype or jQuery. Using window.onload is tricky(see later slides).

    Slightly more work to pass arguments to function (useanonymous function)33

    Example Code: Directly

    JavaScriptfunction makeUpperCase(textfield) {textfield.value = textfield.value.toUpperCase();

    }

    HTML

    34

  • 8/10/2019 JavaScript Browser

    17/26

    Example Output: Directly

    Input was Hellonot HELLO

    35

    Example Code: Indirectly

    JavaScriptfunction makeUpperCase(textfield) {textfield.value = textfield.value.toUpperCase();

    }

    function makeMeUpperCase() {makeUpperCase(this);

    See slide near end about making

    window.onload safer when loading

    multiple JavaScript libraries.

    window.onload = function() {document.getElementById("uppercase-field").onkeyup =makeMeUpperCase;

    }

    36

  • 8/10/2019 JavaScript Browser

    18/26

    Example Output: Indirectly

    Input was This Is a Test

    37

    Passing Events to Event

    Idea JavaScript automatically passes an event object as the last

    argument to event handler functions .

    Sometimes you need the event object for extra info

    General event.type (click, mouseover, etc.)

    event.target (element on which event occurred)

    Mouse events

    event.button (0 = left, 1 = middle, 2 = right)

    event.altKey, event.ctrlKey, event.metaKey, event.shiftKey Booleans indicating if keys were down when mouse event occurred

    even .c en , even .c en , even .screen , even .screen

    Keyboard events

    event.charCode, event.keyCode (see later example)38

  • 8/10/2019 JavaScript Browser

    19/26

    Keyboard Events (onkeypress)

    Internet Explorer se event argument n newer vers ons

    Use window.event in older versionsevent.charCode is numeric character code

    For printable characters, convert to character withString.fromCharCode

    Other browsersUse event in all versionsevent.charCode is numeric character code if character

    Convert to character with String.fromCharCode

    event.keyCode is numeric character code if character wasnonpr n a e arrow, , on ro , e c.

    You must compare to numeric values here

    39

    Example:

    GoalRecognize when Down Arrow is pressed

    When pressed, do whatever pushbutton would have done

    Define handler to take event as argument

    , .Use charCode if defined, otherwise keyCode

    Dont repeat code: programmatically look up the buttonsonclick handler and call it

    40

  • 8/10/2019 JavaScript Browser

    20/26

    Example JavaScript:

    function showValue(inputID, resultID) {=

    "" +

    document.getElementById(inputID).value +" "

    document.getElementById(resultID).innerHTML =html;

    function doOnClickOf(buttonID, event) {var e = event window.eventvar code = e.charCode || e.keyCode;

    if (code == 40) { // 40 is Down Arrowvar f = document. etElementB Id(buttonID).onclick;f();

    }}41

    Example JavaScript:

    " - "

    Sample Text (Hit Down Arrow or Press Button):



    42

  • 8/10/2019 JavaScript Browser

    21/26

    Example Output:

    43

    Mouse Events

    Can capture mouse events on anyelement mages, n s, nput e ements, even norma text

    Event Properties ,

    final argument. To support old browsers, use window.event if event

    undefined, as in revious exam le altKey, ctrlKey, metaKey, shiftKey

    Booleans that tell if key was down when event occurred

    0 for left button, 1 for middle, 2 for right

    clientX, clientY

    screenX, screenY The x and y coordinates relative to the users monitor

    44

  • 8/10/2019 JavaScript Browser

    22/26

    Mouse Event Handlers: Example

    function on(event) {

    = .

    var message =

    "" +" clientX: " + e.clientX + "" +

    " clientY: " + e.clientY + "" +

    " screenX: " + e.screenX + "" +

    " screenY: " + e.screenY + "" +

    "";

    var region = document.getElementById("messageRegion");

    region.innerHTML = message;

    }

    function off() {var reg on = ocumen .ge emen y message eg on ;

    region.innerHTML = "";

    }45

    Mouse Event Handlers: Example

    Here is a heading. What happens when you click on it?

    e se

    Using onmouseover and onmouseout

    ere s a ea ng. a appens w en you move over

    < fieldset>

    46

  • 8/10/2019 JavaScript Browser

    23/26

    Mouse Event Handlers: Example

    47

    Specialized Event Handlers

    input

    For pushbuttons and toggle buttons. Also fires when button is invoked via keyboard.

    onchan e For textfields, when change is committed (focus leaves)

    Use onkeyup for individual characters

    onblur, onfocus form

    onsubmit, onreset Return false to prevent form from really being submitted. Widely used for client-side validation of form fields.

    body onblur, onerror, onfocus, onload, onresize, onunload

    img onabort, onerror, onload

    48

  • 8/10/2019 JavaScript Browser

    24/26

    Specialized Event Handlers:.

    PurposeRun JavaScript code after page is done loading. Used to

    insert HTML in certain regions or to attach eventhandlers to certain HTML elements. Neither can be doneuntil page is done loading

    Simple example (myfile.js)window.onload = function() {

    document.getElementById("").onclick = ;

    document.getElementById("").innerHTML = ;

    }

    49

    window.onload and Multiple

    ProblemAssigning directly to window.onload replaces any

    existing window.onload function.

    .

    Solution

    See if window.onload exists. On Firefix, if no window.onload

    (typeof window.onload == "undefined")

    , . , .

    Either way, you can test !window.onload

    If so, grab the function var o n ow oa unc on = w n ow.on oa ;

    And call it before your window.onload functions

    oldWindowLoadFunction();50

  • 8/10/2019 JavaScript Browser

    25/26

    Safer window.onload

    if (!window.onload) {

    . =

    document.getElementById("").onclick = ;

    document.getElementById("").innerHTML = ;

    };

    } else {

    var oldWindowLoadFunction = window.onload;

    window.onload = function() {

    oldWindowLoadFunction();

    document. etElementB Id("").onclick = ;

    document.getElementById("").innerHTML = ; };

    }

    51

    Additional window.onload

    Problemwindow.onload runs after the entire page (including

    images and style sheets) have been loaded. You have towait until the DOM is arsed but ou shouldnt have towait until after the images have been loaded.

    SolutionsUse window.addEventListener or window.attachEvent But it is tricky to make this portable across browsers

    jQuery) have simple methods for defining code that runsafter the DOM is loaded, but before images and styles ee s are oa e

    52

  • 8/10/2019 JavaScript Browser

    26/26

    Summary

    XMLObtaining document

    request.responseXML or parseFromString (testing only)

    attributes, childNodes, firstChild, nodeName, nodeValue

    getElementsByTagName, getAttribute, normalize

    HTMLMethods and properties

    . ,

    name, id, value, type, disabled, innerHTML

    Event Handling

    someElement.onclick = someFunction;53

    2009 Marty Hall

    Questions?