Client-side JavaScript Notes

The bulk of these notes were taken from/while reading through JavaScript: The Definitive Guide (5th edition) by David Flanagan. Copyright 2006 O'Reilly Media, Inc., 978-0-596-10199-2. Some lines are copied verbatim, but generally, they are 'paraphrased' for better 'personal referencability'. Quoted items are generally linked back to this paragraph. Some other notes were taken from other sources available on the Internet. This document is intended primarily for personal reference.

Table of Contents


Basic Browser Environment

Window object hierarchy

The following table is based on figure 13-1 in JavaScript: The Definitive Guide (5th edition) by David Flanagan. Copyright 2006 O'Reilly Media, Inc., 978-0-596-10199-2.
Current Windowself, window, parent, top (Window objects)
navigator
frames[]
location
history
screen
documentanchors[]
links[]
images[]
applets[]
forms[]elements[]options
Many objects descend from Document object (DOM). Items above are defacto standars and are known as lvl 0 DOM. Most browsers include them.

Getting client-side scripts to run

event handleronclick
  • supported by all button-like form elements, and <a> and <area>.
  • if handler returns false, browser does not perform default button/link action
onmousedown
  • most document elements
onmouseup
  • most document elements
onmouseover
  • when mouse pointer moves over element
onmouseout
  • when mouse pointer moves out of element
onchange
  • <input>, <select>, <textarea>
  • when value changed by user and then changes focus
onload
  • when document and external content (i.e. images) are fully loaded
  • if multiple onload handlers are registered, no guarantee abou the order in which they are invoked.
  • Don't use document.write() calls in onload's.
onunload
  • triggered when user navigates away from web page
  • use to undo/cleanup effects of your onload handler (e.g. close secondary windows)
  • don't popup windows, don't do anything time-consuming
<input type=checkbox name=options value=blah onclick="blah = this.checked;";
function testalert() {
	alert("testing...");
}
<a href="" onclick="testalert(); return(false);">test alert</a>
test alert
//can also assign event handler from external javascript code...
Javascript in URLs <a href="javascript:alert("Hello World!");">test alert</a> test alert
<a href="javascript:window.open('about:blank'); void 0;">open new win</a> open new win
// adding urls this way not considered good form (don't modify link characteristics).
// you can also type the javascript url into the location field of the browser
bookmarklets
  • mini-JavaScript programs that can be easily launched from a menu, toolbar, or bookmarks
//put the following into a link
<a href='javascript:var e="",r="";do{e=prompt("Expression: "+e+"\n"+r+"\n",e);try{r="Result: "+eval(e);}catch(ex){r=ex;}}while(e);void 0;'>JS Evaluator</a>
//search for bookmarklets on the web

Browser compatability

Many ways. The following seem acceptable...

Conditional Comments in IE vs. other browsers

completely non-standard, but seem to work...
html display
...in html <body> section...
<!--[if IE]>
html displayed in IE (only)
<![endif]-->

<!--[if gte IE 6]>
html displayed in IE6+ (only)
<![endif]-->

<!--[if !IE]> <-->
display in browsers other then IE
<!--> <![endif]-->

display in all browsers
JavaScript
/*@cc_on
  @if (@_jscript)
    // jscript is IE javascript
    // var is always set in IE
  @else*/
    //no longer insid a JavaScript comment
    //but still in the IE conditional comment
    //non-IE browsers will run this code
/*@end
  @*/

Browser Windows

Timers

setTimeout()schedules function to function to run after number of milliseconds
  • useful to sched function for delay of 0 milliseconds. Browser invokes function when it has finished running event handlers for any currently pending events, and has finished updating state of doc'.
function alertinfive() { 
	track5 = setTimeout("alert('5 seconds later')",5000);
	return(false);
};
<form><input type="button" value="run in 5 seconds" onclick='alertinfive();'></form>
clearTimeout()
<form><input type="button" value="cancel alert" onclick='clearTimeout(track5); return(false);'></form>
setInterval()function is invoked repeatedly at intervals of specified number of milliseconds
put in example...
clearInterval()use the tracking value to clar the setInterval()
put in example...

Location and History

location propertyholds the URL of the current doc
  • assigning a string value to the window.location property will make browser try to load it as a URL
  • different then document.location or document.URL. This will hold original URL even after a redirect. document.location contains URL as loaded.
reload()reloads currently diplayed page from the web server
replace()loads and displays URL specified, and replaces current URL in browser's history list
href
protocol
host
pathname
searchitems following a question mark in the URL (i.e. parameters)
document.write(location.href.toString() + " - " + location.protocol.toString());

historyback()go back in history list
forward()go forward in history list
go()takes integer arg. Goes forward or backward number of steps in history list.
Mozilla browsers support window.back() and window.forward(). Similar functionality, but may perform different action when used with frames.

Window, Screen, and Browser info

Window/Document Geometry

location
non-IEdefault IEIE doc with <!DOCTYPE> declaration(all vars are read only)
window.document.body.document.documentElement.outerWidth, outerHeightsize of browser win on desktop
screenX, screenY
screenLeft, screenTop (IE)
position of browser win on desktop
innerWidth, innerHeight
clientWidth, clientHeight (IE)
window size minus menu bars, toolbars, scrollbars, etc.
pageXOffset, pageYOffset
scrollleft, scrollTop (IE)
scrollbar positions
scrollWidth, scrollHeight (IE)size of doc

function windowpos() {
	var windowX = 0;
	var windowY = 0;
	if (window.screenLeft) { //IE and others
		windowX = window.screenLeft;
		windowY = window.screenTop;
	}
	else if (window.screenX) {
		windowX = window.screenX;
		windowY = window.screenY;
	}
	var string6 = "windowX - " + windowX + ", windowY - " + windowY;
	alert(string6);
}
<form><input type="button" value="Window Location" onclick='windowpos();'></form>

Screen Object

information about size of display, number of colors available.
width, heightspecify size in pixels.
availWidth, availHeightspecify display size actually available.
availLeft, availTop (non IE)first avail position on the screen.

function screendim() {
	var string7 = "width - " + screen.width + ", height - " + screen.height;
	string7 += ", availWidth - " + screen.availWidth;
	string7 += ", availHeight - " + screen.availHeight;
	alert(string7);
}
<form><input type="button" value="Screen Dimensions" onclick='screendim();'></form>

Navigator Object

var string7;
for(var prop in navigator)
	string7 += prop + ": " + navigator[prop] + "
"; document.write(string7);

Window object

.open
  • pop-up window
  • usually blocked - generally successful only if occurs in response to user action such as clicking on a button or link.
  • return value is window object that can be used to refer to new window.
  • 'opener' property refers to window from which this window was opened. null if user created.
var w = window.open("urltoopen.html", "nameofwindow", "width=400,height=350,resizable=yes...(features), "true(default)/false - create new entry in (other) target windows browsing history");
.close
  • close the window
  • window object continues to exist, but do not attempt to use properties (except testing for window.closed == true. Also, user may have closed window, so continue to check.
moveTo(), moveBy(), resizeTo(), resizeBy()window geometry and placement manipulation. Considered bad form to use them. May be blocked or restricted by browsers.
focus()requests system give window keyboard focus,and move window to top of stacking order
blur()relinquishes keyboard focus
scrollBy()scross doc number of pixels left, right, up or down
scrollTo()scrolls doc to an absolute position
  • html elements have offsetLeft and offsetTop properties that specify X and Y coordinates. You can use this position with scrollTo().
  • elements have focus() method that will also scroll the element to make it visible
  • elements have scrollIntoView which will move window so element is visible
.location.hashwindow.location.hash = "#blah" //will jump to the related <a name=> tag

dialog boxes

not commonly used now-a-days...
alert()
confirm()
confirm box blocks until user closes
prompt()
prompt box blocks until user closes

status line

The status property is generally blocked (misuse). The defaultStatus property is blocked in some browsers. This one sets the default status line when nothing is being hovered over.

Error Handling

//taken from section 14.7 in JavaScript: The Definitive Guide (5th edition) by David Flanagan. Copyright 2006 O'Reilly Media, Inc., 978-0-596-10199-2.
//display no more then 3 error msgs in dialog box
window.onerror = function(msg, url, line) {
	if (onerror.num++ < onerror.max) {
		alert("ERROR: " + msg + "\n" + url + ":" + line);
		return true;
	}
}
onerror.max = 3;
onerror.num = 0;

Frame Relationships

Documents

daname="joe";
document.writeln("hello ");  //puts a newline in, good for <pre>>s
document.write("there " + daname + "<br />");
hi = "hello ";
over = "there ";
document.write(hi, over, daname);

//create/write to another doc in a another window
var ww = window.open();
var dd = ww.document;
dd.open();		//optional
dd.write("hello");	//write into the doc in the other window
dd.close();		//make sure to close the doc or it may not display

Legacy Doc properties

document.
bgColorbackground color of doc. <body> bgcolor attr
cookiehttp cookies
domainused to relax the same-origin security policy somewhat
lastModifiedcontains mod date of doc
locationdeprecated. User URL prop.
referrerURL of doc containing link that brought the browser to curr doc
title<title> of doc
URLURL from which doc was loaded. Sames a window.location.href except in server redirect.

Legacy Doc Obj Collections

document.
anchors[]<a> tag names. .name prop holds name attributes.
//example of getting text from anchors
var a = document.anchors[0];
var text = null;
if (a.text) text = a.text;                          // Netscape 4
else if (a.innerText) text = a.innerText;           // IE 4+
if ((text == null) || (text == '')) text = a.name;  // Default
applets[]Java applets
forms[]
  • <form> elements.
  • Each object has property element[] for each element in form.
  • triger on onsubmit event handler when form submitted. If return false, form is not submitted (i.e. after form validation.

    <form name="f1"><input type="button" name="dabutton" value="f1 test"></form>
    
    document.write("1st - " + document.forms[7].elements[0].attributes[1].nodeValue + "<br />");
    document.write("2nd - " + document.forms[7].elements[0].value + "<br />");
    document.write("3rd - " + document.forms.namedItem("f1").elements[0].value + "<br />");
    document.write("4th - " + document.forms["f1"].elements[0].value + "<br />");
    document.write("5th - " + document.forms.f1.dabutton.value + "<br />");
    document.write("6th - " + document.f1.dabutton.value + "<br />");
    
    <form><input type="button" value="changeit" onclick="document.forms.f1.dabutton.value='changed'; return(false)";></form>
    
images[]src (r/w) property of <img> elements. Used for image-rollovers, simple animations...
links[]
  • href prop of <a> and some <area> tags.
  • href prop in IE replaces both string and href, in firefox it only replaces href. Consider changing string (again) in IE to get it where you want it to be.
  • Properties include protocol, hostname, pathname.
  • triggers on onmouseover, onmouseout, onclick (if event handler returns false, browser will not follow link).
    <a name="yahoolink" id="yahoolink" href="http://www.yahoo.com">www.yahoo.com</a>
    
    if (document.links.yahoolink) {
        document.write(document.links.yahoolink.innerHTML + " - ");
        document.write(document.links.yahoolink.href + " links version<br />");
    } else { //IE6 can't do named links
        dayahoolink = document.getElementById("yahoolink");
        document.write(dayahoolink.innerHTML + " - ");
        document.write(dayahoolink.href + " non-links version<br />");
    }
    
    <input type="button" value="change url" onclick="document.links.yahoolink.href='http://google.com'; return(false);">
    <input type="button" value="change string" onclick="document.links.yahoolink.innerHTML='google.com'; return(false);">
    <input type="button" value="IE change url" onclick="document.getElementById('yahoolink').href='http://google.com'; return(false);">
    <input type="button" value="IE change string" onclick="document.getElementById('yahoolink').innerHTML='google.com'; return(false);">
    
    www.yahoo.com
    Setting event handlers via object interface
    Remember that event handlers can be set as object interfaces...
    document.myform.onsubmit = validateform;
    // no parens needed after function name (don't want to execute here, just want to assign

    Additional DOM information

    More info here

    CSS and DHTML

    Typical attributes used...
    positionstatic | relative | absolute | fixed
    top, left
    bottom, right
    width, height
    z-index
    displayinline | block | inline-block | ...
    visibilityvisible | hidden | collapse
    clip
    overflowvisible | hidden | scroll | auto
    margin, border, padding
    background
    opacityHow opaque or translucent. CSS3. Alternative exists for IE

    Positioning

    Look up in css notes for more specifics
    staticnormal flow
    absolutepositioned independent of other elements. Not part of flow. IE4 only supports absolute positioning of certain elements.
    fixedpositioned with respect to browser window. Not part of flow
    relativeposition adjusted relative to position in normal flow. normal flow space maintained

    To support IE4, wrap absolutely positioned elements in <div> or <span> tags.
    <div style="position: relative; left: 0px; top: 0px; border: 1px solid black; height: 100px; width: 100px;">
        <div style="position: absolute; left: 20px; top: 30px; height: 40px; width: 40px; background-color: blue;">
        </div>
    </div>
    

    Querying position and size

    element.offsetLeftX (left) coord relative to (usually)offsetParrent
    element.offsetTopX (top) coord relative to (usually)offsetParrent
    element.offsetWidth(width)
    element.offsetHeight(height)

    //this example taken directly from JavaScript: The Definitive Guide 
    //(5th edition) by David Flanagan.
    //different browsers handle offsetParent differently, but the following
    //should generally work to determine absolute position of element.
    //doesn't handle overflow attr - check the book for more
    //get x coord of element e
    function getX(e) {
        var x = 0;
        while(e) {
            x += e.offsetLeft;
            e = e.offsetParent; //move up to parent
        }
        return x;
    }
    

    Translucency/Transparency

    /* css */
    opacity: .75;               /* standard CSS3 style for transparency */
    -moz-opacity: .75;          /* transparency for older Mozillas */
    filter: alpha(opacity=75);  /* transparency for IE; no decimal point */
    

    <div style="position: relative; left: 0px; top: 0px; border: 1px solid black; 
    height: 200px; width: 200px;">
        <div style="position: absolute; left: 20px; top: 30px; height: 80px; 
            width: 80px; background-color: red;"></div>
        <div style="position: absolute; left: 50px; top: 50px; height: 80px; 
            width: 80px; background-color: yellow; opacity: .75; -moz-opacity: .75; 
            filter: alpha(opacity=75);"></div>
    </div>
    

    Clipping and Overflow

    See CSS notes for more
    This is what gets clipped.
    style="clip: rect(T R B L)";
    style="clip: rect(0px 100px 100px 0px)";
        OR
    style="clip: rect(auto 100px auto auto)";
    /*auto matches clipping region to edge of element's box*/
    

    This is how what gets clipped is handled.
    visibleoverflow may be drawn ouside elemnt's box
    hiddenoverflow is clipped and hidden
    scrollpermanent horizontal and vertical scrollbars. doesn't usually display on printout
    autoscrollbars if necessary

    Scripting Styles

    Scripting Inline Styles

    1. Find the element by ID, tag name, or recursive traversal
    2. Use element's style property and the particular style property. If particular style property has a dash (-), remove it and make beginning of next word capitalized.
    3. function changefont222() {
          var datext222 = document.getElementById("datext222");
          datext222.style.color = "red";
          datext222.style.fontWeight = "bold";
          datext222.style.border = "2px dashed green";
          datext222.style.position = "absolute";
          datext222.style.top = "30px";
          datext222.style.left = "20px";
      }
      
      <div style="position: relative; left: 0px; top: 0px; height: 80px; 
          width: 500px; border: 1px solid gray">
      <div id=datext222 style="width: 300px; border: 2px solid black;">dis is datext222</div> 
      </div>
      <form><input type=button value="change datext222" onclick="changefont222(); return(false);"></form>
      

      dis is datext222
    4. You can use the element's style property and the particular style property to query attribute values set set explicitly in the style attribute of the element, or set with previous JavaScript.
    5. If properties can have grouped properties (i.e. margin: 0px 5px 20px 0px; then they can be set as one string.
    <div id=containerbox333 style="position: relative; left: 0px; top: 0px; 
            border: 1px solid black; height: 200px; width: 200px;">
        <div id=redbox333 style="position: absolute; left: 20px; top: 30px; height: 80px; 
                width: 80px; background-color: red;"></div>
        <div id=yellowbox333 style="position: absolute; left: 50px; top: 50px; height: 80px; 
                width: 80px; background-color: yellow; opacity: .75; 
                        -moz-opacity: .75; filter: alpha(opacity=75);"></div>
    </div>
    
    var dadir333X = 1;
    var dadir333Y = 2;
    var dayellowdir333X = -2;
    var dayellowdir333Y = -1;
    var tracking333;
    var containerbox333 = document.getElementById("containerbox333");
    var redbox333 = document.getElementById("redbox333");
    var yellowbox333 = document.getElementById("yellowbox333");
    var damaxX = parseInt(containerbox333.style.width) - parseInt(redbox333.style.width);
    var damaxY = parseInt(containerbox333.style.height) - parseInt(redbox333.style.height);
    var damaxYellowX = parseInt(containerbox333.style.width) - parseInt(yellowbox333.style.width);
    var damaxYellowY = parseInt(containerbox333.style.height) - parseInt(yellowbox333.style.height);
    function moveboxes333() {
        var redboxcurX = parseInt(redbox333.style.left);
        var redboxcurY = parseInt(redbox333.style.top);
        var yellowboxcurX = parseInt(yellowbox333.style.left);
        var yellowboxcurY = parseInt(yellowbox333.style.top);
        if ((redboxcurX >= damaxX) || (redboxcurX <= 0)) {
            dadir333X = -1 * dadir333X;
        }
        if ((redboxcurY >= damaxY) || (redboxcurY <= 0)) {
            dadir333Y = -1 * dadir333Y;
        }
        if ((yellowboxcurX >=damaxYellowX) || (yellowboxcurX <= 0)) {
            dayellowdir333X = -1 * dayellowdir333X;
        }
        if ((yellowboxcurY >=damaxYellowY) || (yellowboxcurY <= 0)) {
            dayellowdir333Y = -1 * dayellowdir333Y;
        }
        var danewX = redboxcurX + dadir333X;
        var danewY = redboxcurY + dadir333Y;
        var danewYellowX = yellowboxcurX + dayellowdir333X;
        var danewYellowY = yellowboxcurY + dayellowdir333Y;
        var daXtext = danewX + "px";
        var daYtext = danewY + "px";
        var dayellowXtext = danewYellowX + "px";
        var dayellowYtext = danewYellowY + "px";
        redbox333.style.left = daXtext;
        redbox333.style.top = daYtext;
        yellowbox333.style.left = dayellowXtext;
        yellowbox333.style.top = dayellowYtext;
    }
    function startmove333() {
        tracking333 = setInterval("moveboxes333()",25);
    }
    function stopmove333() {
        clearInterval(tracking333);
    }
    
    <form><input type=button value="start movement" onclick="startmove333(); return(false);">
    <input type=button value="stop movement" onclick="stopmove333(); return(false);"></form>
    

    Getting Computed Styles

    Reading or Setting the Class for an Element

    Enabling/Disabling Stylesheets

    doesn't appear to work in IE6
    testcss1.css
    body {color: black;}
    testcss2.css
    body {color: red;}
    
    function enableSS(sheet) {
        if (sheet == "testcss1") {
            document.getElementById('testcss1').disabled = false;
            document.getElementById('testcss2').disabled = true;
        } else {
            document.getElementById('testcss1').disabled = true;
            document.getElementById('testcss2').disabled = false;
        }    
    }
    
    <form>
    <input type=radio name=choosedastylesheet value=csstest1 checked='checked'
        onclick="enableSS('testcss1')">csstest1
    <input type=radio name=choosedastylesheet value=csstest2 
        onclick="enableSS('testcss2')">csstest2
    </form>
    
    csstest1 csstest2

    Working with Stylesheet attributes

    document.styleSheets[]contains stylesheets
    document.styleSheets[].cssRules[] //W3C
    document.styleSheets[].rules[] //IE
    rules of stylesheets
    • W3C says all rules including things like @import and @page
    • IE only shows actual style rules
    rule.selectorText
    • CSS selector for the rule
    • not defined (in W3C DOM) if not a style rule.
    rule.style
    • CSS2Properties object that describes styles associated with selector
    • not defined (in W3C DOM) if not a style rule.
    document.styleSheets[].insertRule() //W3C
    document.styleSheets[].addRule() //IE
    adding style rule
    document.styleSheets[0].insertRule("H2 { text-weight: bold; }", 0);
    document.styleSheets[0].addRule("H2", "text-weight: bold;", 0);
    document.styleSheets[].deleteTRule() //W3C
    document.styleSheets[].removeRule() //IE
    deleting style rule
    document.styleSheets.deleteRule(rulenumfromarray);
    document.styleSheets.removeRule(rulenumfromarray);

    //taken from JavaScript: The Definitive Guide (5th edition) by David Flanagan.
    //Copyright 2006 O'Reilly Media, Inc., 978-0-596-10199-2
    var ss = document.styleSheets[0];
    //W3C or IE
    var rules = ss.cssRules?ss.cssRules:ss.rules;
    for (var i = 0; i < rules.length; i++) {
        var rule = rules[i];
        //no @import and other nonstyle rules
        if (!rule.selectorText) continue;
        var ruleText = rule.selectorText + " { " + rule.style.cssText + " }";
        
        document.write(ruleText + "<br />");
    }
    

    Events

    There are 3 event models of relevance.

    Original event handlers (i.e. Dom Lvl 0)

    This table is taken directly from table 17-1 in JavaScript: The Definitive Guide (5th edition) by David Flanagan. Copyright 2006 O'Reilly Media, Inc., 978-0-596-10199-2.
    HandlerTriggered whenSupported by
    onabortImage loading interrupted.<img>
    onblurElement loses input focus.<button>, <input>, <label>, <select>, <textarea>, <body>
    onchangeSelection loses focus, and value has changed since it gained focus.<input>, <select>, <textarea>
    onclickmouse press and release; follows mouseup. Return false to cancel default action.most elements
    ondblclickdouble-clickmost elements
    onerrorerror loading image<img>
    onfocuselement gains input focus<button>, <input>, <label>, <select>, <textarea>, <body>
    onkeydownkey pressed down. Return false to cancel.Form elements and <body>
    onkeypresskey pressed; follows keydown. Return false to cancel.Form elements and <body>
    onkeyupkey released; follows keypressForm elements and <body>
    onloaddoc load complete<body>, <frameset>, <img>
    onmousedownmouse button pressedmost elements
    onmousemovemouse movedmost elements
    onmouseoutmouse moves off elementmost elements
    onmouseovermouse moves over elementmost elements
    onmouseupmouse button releasedmost elements
    onresetform reset requested. Return false to prevent.<form>
    onresizewindow size changes<body>, <frameset>
    onselecttext selected<input>, <textarea>
    onsubmitform submission requested. Return false to prevent.<form>
    onunloaddoc or frameset unloaded.<body>, <frameset>
    Event handlers as attributes
    <form>
    <input type="button" value="press me" onclick="alert('first alert'); alert('second alert');">
    </form>
    Event handlers as properties

    DOM Lvl2 Event Handling

    Doesn't work in IE (at least not IE6-).


    eventobject.stopPropagation()during event propagation, event handler calls this method to stop propagation of event.
    eventobject.preventDefault()prevents default action (like the click event of an <a> tag.
    element.addEventListeneradd the handler to the object. Can add multiple, but no guarantee on order.
    object.addEventListener("eventtype",function,true-capturingphase or false-event or bubbling phase)
    document.myform.addEventListener("submit",doSomething, false);

    <div id=dadiv800 style="border: 1px solid gray; width: 200px;">click on me if not IE</div>
    function doSomething() {
    alert("hello");
    }
    dadobject = document.getElementById('dadiv800');
    if (dadobject.addEventListener) {
    dadobject.addEventListener("mousedown",doSomething,false);
    }
    click on me if not IE
    element.removeEventListener()removes event handler registration
    Event modules and types
    You can check to see if browser support module with particular DOM Lvl 2 event with code like:
    document.implementation.hasFeature("MouseEvent", "2.0");

    This table is taken directly from table 17-3 in JavaScript: The Definitive Guide (5th edition) by David Flanagan. Copyright 2006 O'Reilly Media, Inc., 978-0-596-10199-2.
    Event typeInterfaceBubblescan be cancelledSupported by/detail properties
    abortEventyesno<img> <object>
    blurEventnono<a> <area> <button> <input> <label> <select> <textarea>
    changeEventyesno<input> <select> <textarea>
    clickMouseEventyesyesscreenX screenY clientX clientY altKey ctrlKey shiftKey metaKey button detail
    errorEventyesno<body> <frameset> <img> <object>
    focusEventnono<a> <area> <button> <input> <label> <select>
    loadEventnono<body> <frameset> <iframe> <img> <object>
    mousedownMouseEventyesyesscreenX screenY clientX clientY altKey ctrlKey shiftKey metaKey button detail
    mousemoveMouseEventyesnoscreenX screenY clientX clientY altKey ctrlKey shiftKey metaKey
    mouseoutMouseEventyesyesscreenX screenY clientX clientY altKey ctrlKey shiftKey metaKey relatedTarget
    mouseoverMouseEventyesyesscreenX screenY clientX clientY altKey ctrlKey shiftKey metaKey relatedTarget
    mouseupMouseEventyesyesscreenX screenY clientX clientY altKey ctrlKey shiftKey metaKey button detail
    resetEventyesno<form>
    resizeEventyesno<body> <frameset> <iframe>
    scrollEventyesno<body>
    selectEventyesno<input> <textarea>
    submitEventyesyes<form>
    unloadEventnono<body> <frameset>
    DOMActivateUIEventyesyesdetail
    DOMFocusInUIEventyesnonone
    DOMFocusOutUIEventyesnonone
    Event Interface properties & methods
    UIEvent Interface properties
    MouseEvent properties

    IE Event Model

    window.event is a global variable. Some of the properties are:
    typeevent handler name (with "on" removed (e.g. "click" or "mouseover"))
    srcElementelement on which event occurred
    buttonmouse button number pressed (1-left, 2-right, 4-middle)
    clientX, clientYmouse coordinates at time of event relative to upper-left corner of containing window.
    offsetX, offsetYposition of mouse pointer relative to source element (i.e. where in the img there was a click)
    altKey, ctrlKey, shiftKeybooleans that specify whether Alt, Ctrl, or Shirt keys were held down when event occurred.
    keyCodeUnicode char code of keypress event (keydown or keyup).Use String.fromCharChode() to convert to string.
    fromElementfor mouseover events, this specifies the doc element that the mouse came from
    toElementfor mouseout events, this specifies the doc element that the mouse is going to
    cancelBubbleboolean. Set to true to prevent current event from bubbling further up
    returnValueboolean. set to false to prevent browser from performing default action associated with event.

    windows event in IE never get's passed. To duplicate do something like:
    function daEventHandler(event) {
        if (!event) event = window.event;  // get event details for IE
        //rest of function
    }
    //***OR***
    function daEventHandler(e) {
        var event = e || window.event;
        //rest of function
    }
    
    IE Event-Handler Registration
    IE5 and later...
    attachEvent() and detachEvent()...similar to addEventListener() and removeEventListener() except:
    Mouse Events in IE
    setCapture(), releaseCapture()
    Event Handler Memory Leaks
    Something like this will cause a memory leak:
    function addAHandler(form) {
        form.attachEvent("onsubmit", function() { return validate(); };
    }
    To get around this either:

    Mouse Events

    Here's an example from JavaScript: The Definitive Guide (5th edition) by David Flanagan on dragging document elements.

    Key Events


    keyboard input example
    //won't work with cut and paste text, grab onchange handler
    <form>
    <input id="blah6778" type="text" onkeyup="this.value = this.value.toUpperCase();">
    </form>
    
    Type something below

    Synthetic Events

    Fake event sent between handlers - my not be necessary to use in level 0.
    Dispatched events are handled synchronously (you have don't (?) have to wait for call to return)
    If you want to wait for call to return, call setTimeout() with value of 0 milliseconds
    Following is taken from example 17-8 in JavaScript: The Definitive Guide (5th edition) by David Flanagan. Copyright 2006 O'Reilly Media, Inc., 978-0-596-10199-2.
    var DataEvent = {};
    
    DataEvent.send = function(target, datatype, data) {
        if (typeof target == "string") target = document.getElementById(target);
    
        if (document.createEvent) {            // DOM event model
            var e = document.createEvent("Events");
            e.initEvent("dataavailable", true, false); 
        }
        else if (document.createEventObject) { // IE event model
            var e = document.createEventObject();
        }
        else return;  // Do nothing in other browsers
        
        e.datatype = datatype;
        e.data = data;
    
        if (target.dispatchEvent) target.dispatchEvent(e); // DOM 
        else if (target.fireEvent) target.fireEvent("ondataavailable", e); // IE
    };
    
    DataEvent.receive = function(target, handler) {
        if (typeof target == "string") target = document.getElementById(target);
        if (target.addEventListener)
            target.addEventListener("dataavailable", handler, false);
        else if (target.attachEvent) 
            target.attachEvent("ondataavailable", handler);
    };
    

    Forms

    Accessing elements

    document.forms[1].elements[2]
    	OR
    document.<formname>.<elementname>
    
    // Access last form in document
    document.forms[document.forms.length-1]
    
    <form name=daform onreset="return confirm('Really reset the data?')"> <input type=text name=daaddress value="1 Main Street"> <button type=button onclick="setformvalue();">set the text field value</button> <input type=reset> </form> <script type="text/javascript" language="JavaScript"> function setformvalue() { document.daform.daaddress.value = "set value"; return false; }; </script>



    select select multiple

    submit() and reset()

    Submit the form. Reset the form to original settings.

    tags, type property, events

    <input type="button">
    <button type="button">
    "button"onclick
    <input type="checkbox">"checkbox"onclick
    <input type="file">"file"onchange
    <input type="hidden">"hidden"
    <option>
    <input type="password">"password"onchange
    <input type="radio">"radio"onclick
    <input type="reset">
    <button type="reset">
    "reset"onclick
    <select>"select-one"onchange
    <select multiple>"select-multiple"onchange
    <input type="submit">
    <button type="submit">
    "submit"onclick
    <input type="text">"text"onchange
    <textarea>"textarea"onchange

    element properties

    Common event handlers

    Push Buttons

    If onclick event handler returns false, default action of button is not performed.

    Toggle Buttons

    Can do the following with radio buttons or checkboxes.
    <form name=dacheckboxes>
        <input type=checkbox name=dacheckbox value="first" onclick="checkcheckboxes();">first</input><br />
        <input type=checkbox name=dacheckbox value="second" onclick="checkcheckboxes();">second</input><br />
        <input type=checkbox name=dacheckbox value="third" onclick="checkcheckboxes();">third</input><br />
    </form>
    <form name=checkingvalues>
        <input type=text name=valuelisttext value="">
    </form>
    
    <script type="text/javascript" language="JavaScript">
    function checkcheckboxes() {
        var valuelisttext = "";
        for (var i = 0; i < document.dacheckboxes.length; i++) {
            if (document.dacheckboxes.dacheckbox[i].checked) {
                valuelisttext = valuelisttext + document.dacheckboxes.dacheckbox[i].value + " ";
            }
        }
        document.checkingvalues.valuelisttext.value = valuelisttext;
    	return false;
    };
    </script>
    

    first
    second
    third

    select and option

    <form name=blahblah44>
    <select multiple="multiple" name="daoptions44" size="4">
        <option value=one>one</option>
    </select>
    <input type=text name=datext44 value="">
    <button type=button onclick="addvalue44();">add value</button>
    <button type=button onclick="deleteselected44();">delete selected values</button>
    <button type=button onclick="deletevalues44();">delete all values</button>
    <input type=reset></input>
    </form>
    <script type="text/javascript" language="JavaScript">
    function deletevalues44() {
        document.blahblah44.daoptions44.options.length = 0;
        return false;
    }
    function addvalue44() {
        var dalength = document.blahblah44.daoptions44.options.length;
        var datext = document.blahblah44.datext44.value;
        var newoption = new Option(datext, //text property
                                   datext, //value property
                                   false,  //defaultSelected property
                                   false); //selected property
        document.blahblah44.daoptions44.options[dalength] = newoption;
        return false;
    }
    function deleteselected44() {
        var dalength = document.blahblah44.daoptions44.options.length - 1;
        for (var i = dalength; i >= 0; i--) {
            if (document.blahblah44.daoptions44.options[i].selected) {
                //note that options array will compress towards 0
                document.blahblah44.daoptions44.options[i] = null; 
            }
        }
    }
    



    Assigning event to a tag from javascript

    <form name=blah55>
        <button type=button name=clickme55>click me</button>
        <button type=button onclick="enableclickme55();">enable the click me button</button>
    </form>
    
    <script type="text/javascript" language="JavaScript">
    function enableclickme55() {
        //do this onload to make unobtrusive javascript
        document.blah55.clickme55.onclick = function() { showclicked55(); }
    }
    function showclicked55() {
        alert("clicked");
    }
    </script>
    

    Cookies

    Attributes

    Setting, deleting, showing

    document.cookie = "version=" + encodeURIComponent(document.lastModified);
    
    var nextyear = new Date();
    nextyear.setFullYear(nextyear.getFullYear() + 1);
    function setdacookie77 () {
        var dastring77 =  "version=1" +
                          "; max-age=" + (60*60*24*364); 
        document.cookie = dastring77;
    //  document.cookie = "version=" + document.lastmodified +
    //                    "; expires=" + nextyear.toGMTString() +
    //                    "; path=/" +
    //                    "; domain=jungar.net";
        return false;
    }
    function cleardacookie77 () {
        var mydate = new Date();
        mydate.setTime(mydate.getTime() - 1);
        document.cookie = "version=2; max-age=-1";
    //  document.cookie = "version=2; expires=" + mydate.toGMTString();  
    //  document.cookie = "username=; expires=" + mydate.toGMTString(); 
    //  var dastring77 =  "version=" +
    //                    "; expires=" + mydate.toGMTString();
    //                    "; path=/";
    //  document.cookie = dastring77;
        return false;
    }
    function showallcookies77 () {
        var allcookies = document.cookie;
        var checkcookies = decodeURIComponent(allcookies);
        alert ("allcookies - " + checkcookies);
        var dalen = allcookies.length;
        alert("length = " + dalen);
        var pos = allcookies.indexOf("version");
        if (pos != -1) {
            alert("we've got a live one");
            var start = pos + 8;
            var end = allcookies.indexOf(";", start);
            if (end == -1) end = allcookies.length;
            var value = allcookies.substring(start, end);
            value = decodeURIComponent(value);
            alert("value = " + value);
        }
    }
    function cookieenabled77 () {
    //    if (navigator.cookieEnabled != undefined) {
    //        alert("navigator.cookieEnabled - " + navigator.cookieEnabled);
    //    } else {
            document.cookie = "testcookie=test; max-age=10000";
            var cookies = document.cookie;
            if (cookies.indexOf("testcookie=test") == -1) {
                alert("testcookie not set");
            } else {
                alert("testcookie set");
            }
    //    }
    }
    

    XMLHttpRequest

    Methods

    Example

    request.open("GET", url, false, username, password);      // store the request
                                                              // 3rd arg - false=synchronous request/response
                                                              // 4th & 5th arg for svr that needs auth
                                                              // 3rd, 4th, and 5th args optional
    request.setRequestHeader("User-Agent", "XMLHttpRequest"); // set the headers
    request.setRequestHeader("Accept-Language", "en");
    request.setRequestHeader("If-Modified-Since", lastRequestTime.toString());
                                                              // Browser will automatically add relevant cookies
                                                              // unless you add manually
    request.send(null);                                       // send the request
                                                              // GET requests, use null
                                                              // POST requests, send form data
    
    CHECK ON HEADER OPTIONS IN STANDARDS

    Synchronous Response

    if (request.status == 200 {
        var datext = request.responseText;
        // do something with the text
    } else {
        alert("Error " + request.status + "L " + request.statusText);
    }
    
    OR
    
    if {request.status == 200) {
        if (request.getResponseHeader("Content-Type") == "text/xml") { 
            var doc = request.responseXML;
            // Do something with the response document
        }
    }
    

    Asynchronous Response

    XMLHttpRequest readyState values
    0open not called yet
    1opened called, but send not called
    2send called, server has not responded
    3data being received (readyState 3) from server
    firefox sends this multiple times per large doc
    IE sends once at beginning of doc download
    4response is complete

    HTTP Get

    See xmlHttpRequest.js.
    var request = HTTP;newRequest(); //from utility function
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                var datext = request.responseText;
                //do something with datext or request.responeText
            }
        }
    }
    request.open("GET",url); //no 3rd argument - async by default
    //set headers?
    request.send(null); // asynch so no block, return immediately
    

    HTTP POST

    Timeouts

    XML, JSON

    AJAX Examples

    text pull

    <form name=timecompare>
    Browser time
    <input type=text name=localtime value="">
    Server time
    <input type=text name=servertime value="">
    <button type=button onclick="compareTimes();">Show Times</button>
    </form>
    
    <script type="text/javascript" language="JavaScript"> function compareTimes() { var d = new Date(); var localdate = d.getDate(); var localmonth = d.getMonth(); var localyear = d.getFullYear(); var localhour = d.getHours(); var localmin = d.getMinutes(); var localsec = d.getSeconds(); if (localmin < 10) { localmin = "0" + localmin; } if (localsec < 10) { localsec = "0" + localsec; } var localdatetime = localmonth + "/" + localdate + "/" + localyear + " " + localhour + ":" + localmin + ":" + localsec; document.timecompare.localtime.value = localdatetime; HTTP.getText("/AJAXDomJavaScript/proutdate.php",putsvrtime); return false; } function putsvrtime(datext) { document.timecompare.servertime.value = datext; } </script>
    <?php echo date('n/j/Y G:i:s'); ?>

    Browser time Server time

    xml pull

    <form name=xmlview>
    <textarea name=textversion rows=8 cols=80></textarea>
    <br /><br />
    <u>DOM table<u>
    <div id=xmlversion class=boxedmono></div>
    <br />
    <u>Character names and descriptions only</u>
    <div id=characters class=boxedmono></div>
    <button type=button onclick="grabdaxml();">Grab the XML</button>
    </form>
    
    function grabdaxml() { HTTP.getXML("/AJAXDomJavaScript/proutxml2.php",putdaxml); return false; } var totaltable = ""; var totaltable2 = ""; function putdaxml(daxml, datext) { document.xmlview.textversion.value = datext; //initialize totaltable totaltable = (put in the table header row for nodeType, nodeName, nodeValue, textContent, Data...) totaltable2 = "<table class=mono>" + "<tr>" + "<th>name</th>" + "<th>desc</th>" + "</tr>"; //grab the dom var n = daxml.documentElement; var children = n.childNodes; var depthstring = "-"; lookforxmltext(children, depthstring); totaltable = totaltable + "</table>" //insert table into the xmlversion div var xmlversion = document.getElementById("xmlversion"); xmlversion.innerHTML = totaltable; //grab the characters nodes only var characternodes = n.getElementsByTagName("character"); lookforcharacters(characternodes); totaltable2 = totaltable2 + "</table>" //insert table into the characters div var xmlversion = document.getElementById("characters"); xmlversion.innerHTML = totaltable2; } function lookforcharacters(characternodelist) { for (var i=0; i < characternodelist.length; i++) { // going to assume that things are in the right order for now // need to check on name because you can get /n and whitespace... if (characternodelist[i].nodeName == "name") { totaltable2 = totaltable2 + "<tr>" + "<td>" + characternodelist[i].textContent + "</td>"; } if (characternodelist[i].nodeName == "desc") { totaltable2 = totaltable2 + "<td>" + characternodelist[i].textContent + "</td>" + "</tr>"; } // in case there's anything deeper if (characternodelist[i].childNodes.length > 0) { lookforcharacters(characternodelist[i].childNodes); } } } function lookforxmltext(Childlist, depthstring) { for (var i=0; i < Childlist.length; i++) { totaltable = totaltable + "<tr>" + "<td>" + depthstring + "</td>" + "<td>" + i + "/" + Childlist.length + "</td>" + "<td>" + Childlist[i].nodeType + "</td>" + "<td>" + Childlist[i].nodeName + "</td>" + "<td>" + Childlist[i].nodeValue + "</td>" + "<td>" + Childlist[i].textContent + "</td>" + "<td>" + Childlist[i].Data + "</td>" + "</tr>"; if (Childlist[i].childNodes.length > 0) { depthstring2 = depthstring + "-"; lookforxmltext(Childlist[i].childNodes, depthstring2); } }
    <?php header('Content-type: text/xml'); $xmlstr = <<<XML <?xml version='1.0' standalone='yes'?> (xml for book with title characters, and plot) XML; $xml = new SimpleXMLElement($xmlstr); echo $xml->asXML(); //echo $xml->book[0]->plot; ?>
    Text version


    DOM table

    Character names and descriptions only
    NEED TO TRY SEND DATA IN POST AND GET RESPONSE
    NEED TO TRY SEND XML AND GET RESPONSE