11103 Lecture Slides

Embed Size (px)

Citation preview

  • 8/10/2019 11103 Lecture Slides

    1/72

    Min Wu

    [email protected]

    JavaScript Programming

    ITU 2014

  • 8/10/2019 11103 Lecture Slides

    2/72

    Topics

    JavaScript has a programming language Variables, data types, functions

    OOP

    Using JavaScript to access BOM and DOM

    JavaScript event handling

    ITU 2014

  • 8/10/2019 11103 Lecture Slides

    3/72

    Recommended book

    Professional JavaScript for Web Developers (3rd edition)

    http://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/ref=sr_1_8?ie=UTF8&qid=1346488523&sr=8-8&keywords=javascript+programming

    ITU 2014

    http://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/ref=sr_1_8?ie=UTF8&qid=1346488523&sr=8-8&keywords=javascript+programminghttp://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/ref=sr_1_8?ie=UTF8&qid=1346488523&sr=8-8&keywords=javascript+programminghttp://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/ref=sr_1_8?ie=UTF8&qid=1346488523&sr=8-8&keywords=javascript+programminghttp://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/ref=sr_1_8?ie=UTF8&qid=1346488523&sr=8-8&keywords=javascript+programminghttp://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/ref=sr_1_8?ie=UTF8&qid=1346488523&sr=8-8&keywords=javascript+programminghttp://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/ref=sr_1_8?ie=UTF8&qid=1346488523&sr=8-8&keywords=javascript+programminghttp://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/ref=sr_1_8?ie=UTF8&qid=1346488523&sr=8-8&keywords=javascript+programminghttp://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/ref=sr_1_8?ie=UTF8&qid=1346488523&sr=8-8&keywords=javascript+programminghttp://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/ref=sr_1_8?ie=UTF8&qid=1346488523&sr=8-8&keywords=javascript+programminghttp://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/ref=sr_1_8?ie=UTF8&qid=1346488523&sr=8-8&keywords=javascript+programminghttp://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/ref=sr_1_8?ie=UTF8&qid=1346488523&sr=8-8&keywords=javascript+programminghttp://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/ref=sr_1_8?ie=UTF8&qid=1346488523&sr=8-8&keywords=javascript+programminghttp://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/ref=sr_1_8?ie=UTF8&qid=1346488523&sr=8-8&keywords=javascript+programminghttp://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/ref=sr_1_8?ie=UTF8&qid=1346488523&sr=8-8&keywords=javascript+programminghttp://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/ref=sr_1_8?ie=UTF8&qid=1346488523&sr=8-8&keywords=javascript+programminghttp://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/ref=sr_1_8?ie=UTF8&qid=1346488523&sr=8-8&keywords=javascript+programming
  • 8/10/2019 11103 Lecture Slides

    4/72

    Tools

    XAMPPServer-side support

    NetBeans IDE PHP bundle

    Firefox

    FirebugFirefox extension for JavaScript debugging

    ITU 2014

  • 8/10/2019 11103 Lecture Slides

    5/72

    Grading policy

    In-class coding quizzes60% Bring your laptop all the time

    Do not plagiarism. Identical code means F grade.

    In-class final exam40%

    Open book

    No electronic device

    Attendance is required.

    ITU 2014

  • 8/10/2019 11103 Lecture Slides

    6/72

    JavaScript components

    The Core (ECMAScript)Script language specification DOMAPI to access and manipulate XML: add, remove,

    replace, modify DOM nodes

    BOMaccess and manipulate the browser window No standard and each browser has its own implementation

    Source: Professional JavaScript for Web DevelopersITU 2014

  • 8/10/2019 11103 Lecture Slides

    7/72

    JavaScript in HTML

    element Type attribute: required. text/javascript

    Src attribute: optional. External JS file that contains code to beexecuted

    Put the script code in

    Put the script code at the end of

    Inline code vs. external file

    Code reuse Maintainability

    Caching

    Obtrusive JavaScript

    ITU 2014

  • 8/10/2019 11103 Lecture Slides

    8/72

    JavaScript basics

    Case sensitive Identifier vs. reserved words

    Statements terminated by a semicolon

    Loosely-typed variable A variable can hold any type of data and is simply a named

    placeholder for a value

    var operator to define/declare a variable and make it localto

    the scope in which it is defined

    ITU 2014

  • 8/10/2019 11103 Lecture Slides

    9/72

    Data types

    Undefined Null

    Boolean

    Number

    String

    Object Unsorted list of name-value pairs

    There is no way to define your own data type in ECMAScript

    Array

    Function

    ITU 2014

  • 8/10/2019 11103 Lecture Slides

    10/72

    Typeof operator

    undefined if the value is undefined boolean if the value is a Boolean

    string if the value is a string

    number if the value is a number object if the value is an object or null

    function if the value is a function

    Functions are objects with special properties

    ITU 2014

  • 8/10/2019 11103 Lecture Slides

    11/72

    Undefined type

    Only one value: undefined When a variable is declared using var but not initialized

    Variable containing the value of undefined vs. variable thathas not been defined at all

    ITU 2014

  • 8/10/2019 11103 Lecture Slides

    12/72

    Null type

    Only one value: null Null value is an empty object pointerthe variable will later

    hold an object

    Undefined vs. null

    Never explicitly set the value of a variable to undefined

    Any time an object is expected but is not available, null shouldbe used in its place. This helps to keep the paradigm of null as anempty object pointer and further differentiates it fromundefined

    ITU 2014

  • 8/10/2019 11103 Lecture Slides

    13/72

    Boolean type

    Two literal values: true and false Boolean( ) casting function

    false, hellotrue

    0false, NaNfalse, 10true, Infinitytrue

    new Object()true, any objecttrue

    nullfalse

    undefinedfalse

    ITU 2014

  • 8/10/2019 11103 Lecture Slides

    14/72

    Number type

    Both integers and floating-point values Integers

    base 10, 8, 16 All the integers are signed in ECMAScript

    Range

    Number.MIN_VALUE, Number.MAX_VALUE Infinity (Number.POSITIVE_INFINITY), -Infinity

    (Number.NEGATIVE_INFINITY) isFinite()

    NaN: when an operation intended to return a number has failed (asopposed to throwing an error) A special numeric value NaN is not equal to any value, including NaN isNaN(): determine if a value is not a number or cannot be converted to a

    number

    ITU 2014

  • 8/10/2019 11103 Lecture Slides

    15/72

    Number conversions

    Number() true1, false0

    null0

    undefinedNaN

    0, helloNaN

    parseInt(string [, radix])

    NaN

    parseFloat(string)

    ITU 2014

  • 8/10/2019 11103 Lecture Slides

    16/72

    String type

    Double quotes or single quotes string.length property

    Strings are immutable in ECMAScript

    ITU 2014

  • 8/10/2019 11103 Lecture Slides

    17/72

    String conversions

    String(): nullnull

    undefinedundefined

    obj.toString():

    obj cannot be null or undefined

    Optional radix for num.toString()

    ITU 2014

  • 8/10/2019 11103 Lecture Slides

    18/72

    Equality

    Equal (==) and not equal (!=) If an operand is Boolean, convert it into the numeric value

    If an operand is string and the other is a number, convert the stringinto a number

    If an operand is an object, first call valueOf() and then toString()

    For example: 55 == 55 // true

    null == undefined // true

    null == 0 // false

    undefined == 0 // false

    NaN == NaN // false

    Identically equal (===) and not identically equal (!==) No conversion

    ITU 2014

  • 8/10/2019 11103 Lecture Slides

    19/72

    Functions

    function functionName(arg0, arg1,...,argN) {statements

    }

    return statement return; // return a undefined value

    Function arguments arguments.length

    arguments[0],

    All arguments are passed by value

    No overloading Functions in ECMAScript do not have signatures

    The last function definition counts if functions have the same name

    ITU 2014

  • 8/10/2019 11103 Lecture Slides

    20/72

    Primitive and reference values

    Primitive value: the value is completely stored in onememory location

    5 primitive types: Undefined, Null, Boolean, Number, String

    Reference value: the value stored in the variable is actually

    just a pointer to another memory location where the objectis stored

    Dynamic properties: properties and methods may be added,changed, or deleted at any time

    Primitive values can t have properties

    ITU 2014

  • 8/10/2019 11103 Lecture Slides

    21/72

    Assignment

    When a primitive value isassigned from one variable toanother, the value is createdand copied into the location

    for the new variable

    When a reference value isassigned from one variable toanother, the pointer is copiedinto the location for the newvariable

    Source: Professional JavaScript for Web DevelopersITU 2014

  • 8/10/2019 11103 Lecture Slides

    22/72

    Execution context

    Global: the window object Global variable and top-level function: dynamic properties

    added to the window object

    Local (function)

    Scope chain: provide ordered access to all variables andfunctions that an execution context has access to

    Variable declaration: when a variable is declared using var, it isautomatically added to the most immediate context available.

    No block-level scope

    ITU 2014

  • 8/10/2019 11103 Lecture Slides

    23/72

    The Object type

    Create an instance new operator with Object constructor

    Object literal notation

    Access property

    Dot notation

    Bracket notation: string containing the property name

    ITU 2014

  • 8/10/2019 11103 Lecture Slides

    24/72

    The Array type

    Create an array (new operator with) Array constructor: can pass size or items

    Array literal notation

    Length

    Length can be dynamically updated

    toString() method

    ITU 2014

  • 8/10/2019 11103 Lecture Slides

    25/72

    The Array related methods

    ITU 2014

    Push(): add elements to the end; return new array length Pop(): remove the last element; return the removed (last) element

    Unshift(): add elements to the front; return new array length

    Shift(): remove the first element; return the removed (first)

    element

    Stack: last-in-first-out (LIFO) - push and pop

    Queue: first-in-first-out (FIFO)push and shift

    Reverse() Sort()

    Default: ascending order; comparing the string value of the arrayelements

    Sort with comparison function

  • 8/10/2019 11103 Lecture Slides

    26/72

    The Array manipulation methods

    ITU 2014

    Concat() Create and return a new copy of an array

    Append the method arguments (elements or arrays)

    Slice(starting_index, stopping_index)

    Create and return a new array that contains a section of theoriginal array

    Stopping index is optional

    Element at the stopping index is not included

    Splice(starting_index, how_many, element1, , elementN)

    Deletion: no element included in the method argument

    Insertion: how_many=0

    Replacement

  • 8/10/2019 11103 Lecture Slides

    27/72

    The Date type

    ITU 2014

    Store Date type as the number of milliseconds that have passedsince midnight on January 1, 1970 Universal Time Code (UTC)

    new Date(): date object that is assigned the current data and time

    new Date(milliseconds)

    Date.parse(string_representation_of_date): return millisecondsfor the current time zone that can be used by new Date() orNaN

    month/date/year: 6/13/2012

    month_name date, year May 25, 2012

    Date.UTC(year, month(0, 11), day(1, 31), hours(0, 23),minutes(0, 59), seconds(0, 59), milliseconds): return milliseconds

    for UTC

  • 8/10/2019 11103 Lecture Slides

    28/72

    The Date type methods

    ITU 2014

    Date formatting toDateString(), toTimeString()

    toLocalDateString(), toLocalTimeString()

    Date/time components

    getFullYear, setFullYear, getUTCFullYear, setUTCFullYear

    getMonth, setMonth, getUTCMonth, setUTCMonth

    getDate, setDate, getUTCDate, setUTCDate (day of month)

    getDay, getUTCDay (day of week)

    getHours, setHours, getUTCHours, setUTCHours; Minutes;Seconds; Milliseconds

    getTimezoneOffset

  • 8/10/2019 11103 Lecture Slides

    29/72

    The Function type

    ITU 2014

    Functions are objects Function names are pointers to function objects

    Named functions are the same as anonymous functions assigned tonamed variables

    No overloading (no two functions with the same name) Function declaration can be after function execution; function

    expression has to be before function execution

    Function declaration is always evaluated before functionexpression, does not matter where they appear in the code.

    function foo() { return hello;} // function declarationvar foo = function() { return world;}; // function expressionfoo(); // world

  • 8/10/2019 11103 Lecture Slides

    30/72

    Function as values

    ITU 2014

    Function can be assigned to a variable Function can be passed to another function as argument

    Function can be returned from another function as returnvalue

  • 8/10/2019 11103 Lecture Slides

    31/72

    Function properties

    ITU 2014

    Arguments Arguments.callee

    Length

    The number of arguments that the function expects

  • 8/10/2019 11103 Lecture Slides

    32/72

    this object and function scope

    ITU 2014

    this refers to the object that the function is operating on, orthis refers to the scope in which the function is beingexecuted

    2 methods for function objects: apply(), call()

    Execute function in a specific scope

    apply(scope, [argument array]): function arguments are put intoan array

    call(scope, arg1, , argN): function arguments are listed after

    the scope

  • 8/10/2019 11103 Lecture Slides

    33/72

    JavaScript OOP

    ITU 2014

    Create a custom object var person = new Object();

    Issue: duplicated code

    Factory pattern

    Using a create function Issue: no object identification

    Constructor pattern Using constructora normal function, but called by the new

    operator Using global function to avoid unique function object for

    individual objects

    Issue: create clutter in the global scope by introducing afunction that are used only in relation to an object

  • 8/10/2019 11103 Lecture Slides

    34/72

    JavaScript OOP prototype pattern

    ITU 2014

    Each function is created with a special property calledprototype

    Each instance created by the constructor has an internalpointer __proto__

    Source: Professional JavaScript for Web Developers

  • 8/10/2019 11103 Lecture Slides

    35/72

    Prototype pattern (II)

    ITU 2014

    Property access: begin with the instance; if the property isnot found, continue up to the prototype

    The property on the instance shadows the property with thesame name on the prototype

    hasOwnProperty(): true only if the property exists on theinstance

    In operator: true if the property is accessible by the object,which means that the property is either on the instance or onthe prototype

    For-in loop for all the accessible properties by an object

  • 8/10/2019 11103 Lecture Slides

    36/72

    Combination of constructor/prototype

    pattern

    ITU 2014

    Constructor pattern defines instance properties Prototype pattern defines methods and shared properties

  • 8/10/2019 11103 Lecture Slides

    37/72

    Dynamic Prototype Pattern

    ITU 2014

    Using prototype inside constructor

    Only one definition block

  • 8/10/2019 11103 Lecture Slides

    38/72

    Inheritance

    ITU 2014

    Two types of inheritance from OOP Interface inheritanceonly the method signatures are inherited

    Implementation inheritanceactual methods are inherited

    JavaScript only supports implementation inheritance since

    JavaScript function does not have signature.

  • 8/10/2019 11103 Lecture Slides

    39/72

    Prototype chaining

    ITU 2014

    Use prototype to inherit properties and methods betweentwo reference types

    An instance from SuperType is assigned as the prototypeobject of SubType: SubType.prototype = new SuperType();

    Source: Professional JavaScript for Web Developers

  • 8/10/2019 11103 Lecture Slides

    40/72

    Constructor stealing

    ITU 2014

    Call SuperType constructor from within SubTypeconstructor:function SubType() {

    SuperType.call(this);

    } No inheritance. No prototype chaining

    The result is that each SubType instance has (steals) its owncopy of the properties from SuperType

  • 8/10/2019 11103 Lecture Slides

    41/72

    Combination inheritance

    ITU 2014

    Prototype chaining + constructor stealing Prototype chaining to inherit the properties and methods on

    the prototype

    Constructor stealing to inherit the instance properties

    Most frequently used inheritance pattern in JavaScript

  • 8/10/2019 11103 Lecture Slides

    42/72

    Private variables

    ITU 2014

    All object properties in JavaScript are public

    Create private variables for reference types

    Define all private variables inside the constructor

    Define public methods to access the private members

  • 8/10/2019 11103 Lecture Slides

    43/72

    Browser Object Model (BOM)

    ITU 2014

    Browser functionality that is independent from any web pagecontent

    There is no standard BOM implementation or standard BOMinterfaces across different major browsers.

  • 8/10/2019 11103 Lecture Slides

    44/72

    Three main BOM objects

    ITU 2014

    The window object An instance of the browser

    Global object that specifies the global scope

    The location objectwindow.location

    Information about the document that is currently loaded

    Supporting navigation functionality

    The history objectwindow.history

    Users navigation history

  • 8/10/2019 11103 Lecture Slides

    45/72

    Opening windows

    ITU 2014

    window.open(url, target, specs, replace) Url

    If no url, a new window with about:blank

    Target

    _blank: new window/tab (default behavior) When no specs, a new tab is open

    When specs is specified, a new window is open

    _self : the current window is reloaded

    name: a name of a windowwindow.open(url1, myWin);window.open(url2. myWin); // open another url in the samewindow/tab

  • 8/10/2019 11103 Lecture Slides

    46/72

    Open windows (cont.)

    ITU 2014

    Specs: a comma - delimited string of settings indicatingdisplay information for the new window

    Height, left, top, widthposition and size

    Location, menubar, toolbar, statuswhether a browser

    component should be displayed Resizable

    Scrollbars

    Replace: whether the URL creates a new entry or replaces

    the current entry in the history list

  • 8/10/2019 11103 Lecture Slides

    47/72

    Intervals and timeouts

    ITU 2014

    var timer = setTimeout(function () {}, milliseconds); clearTimeout(timer);

    Function is triggered at a later time

    var intervalId = setInterval(function () {}, milliseconds);

    clearInterval(intervalId);

    Function is triggered repeatedly

  • 8/10/2019 11103 Lecture Slides

    48/72

    System dialogs

    ITU 2014

    Alert(): message box without controls

    Var result = Confirm(): confirmation dialog with OK and Cancelbuttons Result is true if OK is clicked

    Result is false if Cancel is clicked

    Var result = Prompt(): dialog for users input with OK and Cancelbuttons Result is the value in the text box if OK is clicked.

    Result is null if Cancel is clicked or the dialog is closed without

    clicking OK. Window.print()display browsers print dialog

    Window.find()display browsers find dialog

  • 8/10/2019 11103 Lecture Slides

    49/72

    The location object

    ITU 2014

    The location properties Host

    Hostname

    Port

    Href: full URL Pathname

    Protocolhttp: or https:

    Searchquery string of the URL, starting with ?

  • 8/10/2019 11103 Lecture Slides

    50/72

    The location object (cont.)

    ITU 2014

    Navigation Location.assign(url)same as

    Window.loaction = url

    Location.href = url

    Location.replace(url)the current page will not be in thehistory stack

    Location.reload(true)retrieve from the server again

  • 8/10/2019 11103 Lecture Slides

    51/72

    The history object

    ITU 2014

    Each browser window/tab has its own history object. History.go(number_of_steps)

    -1: back

    1: forward

    2: forward 2 pages

    History.back(), history.forward()

    History.lengththe size of the history stack

  • 8/10/2019 11103 Lecture Slides

    52/72

    Document Object Model (DOM)

    ITU 2014

    A hierarchy of nodes from HTML/XML document 12 node types

    Node.ELEMENT_NODE (1)

    Node.ATTRIBUTE_NODE (2)

    Node.TEXT_NODE (3)

    Node.DOCUMENT_NODE (9)

  • 8/10/2019 11103 Lecture Slides

    53/72

    Node types

    ITU 2014

    Node.ELEMENT_NODE (1) ATTRIBUTE_NODE (2)

    TEXT_NODE (3)

    CDATA_SECTION_NODE (4)

    ENTITY_REFERENCE_NODE (5)

    ENTITY_NODE (6)

    PROCESSING_INSTRUCTION_NODE (7)

    COMMENT_NODE (8)

    DOCUMENT_NODE (9) DOCUMENT_TYPE_NODE (10)

    DOCUMENT_FREGMENT_NODE (11)

    NOTATION_NODE (12)

  • 8/10/2019 11103 Lecture Slides

    54/72

    ITU 2014

    document (9)

    comment node (8)

    document type node (10)

    element node (1)

  • 8/10/2019 11103 Lecture Slides

    55/72

    Node relationship

    ITU 2014

    childNodes: a NodeList that stores an ordered list of the childnodes that are accessible by position/index

    childNodes[i]

    firstChild

    lastChild

    parentNode

    nextSibling

    previousSibling Source: Professional JavaScript for Web Developers

  • 8/10/2019 11103 Lecture Slides

    56/72

    Document node

    ITU 2014

    nodeType: 9

    nodeName: #document

    nodeValue: null

    parentNode: null

    document.body // reference to the element

    document.documentElement // reference to the element

    document.title

    document.URL

    document.domain

    document.referrer

  • 8/10/2019 11103 Lecture Slides

    57/72

    Locating elements

    ITU 2014

    document.getElementById(idname) // return the firstelement in the document with idname

    document.getElementsByTagName(tagname) // returnHTMLCollection object

    document.getElementsByName(name) // returnHTMLCollection object

    Special collections

    Document.anchors

    Document.forms

    Document.images

    Document.links

  • 8/10/2019 11103 Lecture Slides

    58/72

    Element node

    ITU 2014

    nodeType: 1 nodeName: tag name

    nodeValue: null

    Standard attributes Id: element.id

    Class: element.className

    Titletooltip: element.title

    getAttribute(attrName) and setAttribute(attrName,attrValue) Work with custom attributes

  • 8/10/2019 11103 Lecture Slides

    59/72

    Text node

    ITU 2014

    nodeType: 3 nodeName: #text

    nodeValue: the text contained in the node

    No child nodes

  • 8/10/2019 11103 Lecture Slides

    60/72

    Manipulating nodes

    ITU 2014

    pNode.appendChild(newChild) pNode.insertBefore(newChild, someChild)

    pNode.replaceChild(newChild, oldChild)

    pNode.removeChild(removedChild)

    newENode = document.createElement(tagName)

    newTNode = document.createTextNode(content)

    newNode.setAttribute(attr_name, attr_value)

    newNode = oldNode.cloneNode([true]) // deep clone

    newNode = oldNode.cloneNode(false) // shallow clone

  • 8/10/2019 11103 Lecture Slides

    61/72

    Attribute node

    ITU 2014

    nodeType: 2 nodeName: attribute name

    nodeValue: attribute value

    parentNode: null

    element.getAttributeNode(attrName)

    element.setAttributeNode(attrNode)

  • 8/10/2019 11103 Lecture Slides

    62/72

    Event flow

    ITU 2014

    The order in which events are received on the page Event bubbling: event starts at the most specific element and

    then flows upward towards the least specific node(document)

    Event capturing: the least specific node (document) receivesthe event first, and the most specific node receive the eventlast

    Source: Professional JavaScript

    for Web Developers

  • 8/10/2019 11103 Lecture Slides

    63/72

    Event handling

    ITU 2014

    A function is called in response to an event Naming convention

    Events: click, load, mouseover

    Event handlers: onclick, onload, onmouseover

    HTML event handlersHTML attribute with the name ofthe event handler

    DOM level 0 event handlersDOM elements with eventhandler properties

    Remove event handler by setting the event handler propertiesto null

  • 8/10/2019 11103 Lecture Slides

    64/72

    Event handling (cont.)

    ITU 2014

    DOM level 2 event handlersaddEventListener /removeEventListener

    Can specify whether to call the event handler during thecapture phase or during the bubbling phase

    Can add multiple event handlers for a single DOM element

  • 8/10/2019 11103 Lecture Slides

    65/72

    Event object

    ITU 2014

    When an event related to the DOM is fired, all of therelevant information is gathered and stored on an objectcalled event.

    eventis a special variable for the event object in HTML event

    handler Properties: type, target, currentTarget, eventPhase

    Methods: preventDefault(), stopPropagation()

  • 8/10/2019 11103 Lecture Slides

    66/72

    Mouse events

    ITU 2014

    Click, dblclick, mousedown, mouseup, mouseout,mouseover, mousemove

    click event can only be fired if a mousedown event is fired andfollowed by a mouseup event on the same element.

    Event object properties Coordinates: clientX, clientY, screenX, screenY

    Modifier keys: shift, ctrl, alt, meta

    Button: which mouse button is pressed/released (mousedown

    and mouseup events only)

  • 8/10/2019 11103 Lecture Slides

    67/72

    Keyboard events

    ITU 2014

    Keydown, keypress, keyup A character key is pressed: keydown, keypress, (any changes

    made to the text box,) and then keyup

    A non-character key is pressed: keydown, and then keyup

    Event object properties KeyCode: for keydown and keyup events

    CharCode: for keypress event only

    Using String.fromCharCode(charCode) to covert the character

    code to the actual character

  • 8/10/2019 11103 Lecture Slides

    68/72

    HTML events

    ITU 2014

    Load, unloadrelated to web pages

    Resizerelated to the browser window

    Focus, blurrelated to any DOM element

  • 8/10/2019 11103 Lecture Slides

    69/72

    HTML events

    ITU 2014

    Load, unloadrelated to web pages Image can fire load event too.

    Image load event is fired before the window load

    event. That is, window.onload is triggered after

    image.onload. Resizerelated to the browser window

    Focus, blurrelated to any DOM element

    elem.focus()set elem in focus

    Select, change, submit, resetrelated to form and itsincluded DOM elements

  • 8/10/2019 11103 Lecture Slides

    70/72

    Form-related events

    ITU 2014

    Change event from Input text field

    Select widget

    Checkbox

    Etc. Select event from

    Input text field

    Text area

  • 8/10/2019 11103 Lecture Slides

    71/72

    Mutation events

    ITU 2014

    DOMSubtreeModified

    DOMNodeInserted

    DOMNodeRemoved

    Can always add them to the document, and useevent.target.id to find out which element actually fired thoseevents

  • 8/10/2019 11103 Lecture Slides

    72/72

    Mutation events

    Events fired when the DOM tree structure has changed DOMSubtreeModified

    DOMNodeInserted

    DOMNodeRemoved

    Use event.target.id to find out which element actually firedthose events

    Events fired when the DOM node content has changed

    DOMAttrModified

    DOMCharacterDataModified