WebSocket Properties readonly unsigned long bufferedAmount The number of characters of text that have been passed to send() but not yet actually sent. If you need to send large amounts of data, you can use this property to ensure that you are not sending messages faster than they can be transmitted. readonly string protocol If an array of subprotocols was passed to the WebSocket() constructor, this property holds the one chosen by the server. Note that when the WebSocket is first created, the con- nection is not established and the server’s choice is not known. So this property starts as the empty string. If you passed protocols to the constructor, this property will change to reflect the server’s choice of subprotocol when the open event is triggered. readonly unsigned short readyState The current state of the WebSocket connection. This property holds one of the constant values listed above. readonly string url This property holds the URL that was passed to the WebSocket() constructor. Methods void close() If the connection is not already closed or closing, this method begins the process of closing it, setting readyState to CLOSING. Message events may continue to be fired even after close() is called, until readyState changes to CLOSED and the close event is fired. void send(string data) This method sends the specified data to the server at the other end of the WebSocket con- nection. This method throws an exception if called before the open event has been triggered, while readyState is still CONNECTING. The WebSocket protocol supports binary data, but at the time of this writing, the WebSocket API only allows strings to be sent and received. Event Handlers Network communication is inherently asynchronous, and like XMLHttpRequest, the Web- Socket API is event-based. WebSocket defines four event handler registration properties, and also implements EventTarget, so you can also register event handlers using the EventTarget methods. The events described below are all fired at the WebSocket object. None of them bubble, and none have a default action to cancel. Note, however, that they do have different event objects associated with them. onclose A close event is triggered when the WebSocket connection closes (and readyState changes to CLOSED). The associated event object is a CloseEvent, which specifies whether the connection closed cleanly or not. onerror An error event is triggered when a network or WebSocket protocol error occurs. The associated event object is a simple Event. 1000 | Client-Side JavaScript Reference
Window onmessage When the server sends data through the WebSocket, the WebSocket fires a message event, with an associated MessageEvent object whose data property refers to the received message. onopen The WebSocket() constructor returns before the connection to the specified url is estab- lished. When the connection handshake completes and the WebSocket is ready to send and receive data, an open event is fired. The associated event object is a simple Event. Window a web browser window, tab, or frame EventTarget The Window object represents a browser window, tab, or frame. It is documented in detail in Chapter 14. In client-side JavaScript, the Window serves as the “global object,” and all expressions are evaluated in the context of the current Window object. This means that no special syntax is required to refer to the current window, and you can use the properties of that window object as if they were global variables. For example, you can write document rather than window.document. Similarly, you can use the methods of the current window object as if Reference JavaScript Client-Side they were functions: e.g., alert() instead of window.alert(). Some of the properties and methods of this object actually query or manipulate the browser window in some way. Others are defined here simply because this is the global object. In addition to the properties and methods listed here, the Window object also implements all the global properties and functions defined by core JavaScript. See Global in Part III for details. Web browsers fire many kinds of events at windows. This means that the Window object defines quite a few event handlers, and that Window objects implement the methods defined by EventTarget. The Window object has window and self properties that refer to the window object itself. You can use these to make the current window reference explicit rather than implicit. A Window can contain other Window objects, typically in the form of <iframe> tags. Each Window is an array-like object of nested Window objects. Rather than indexing a Window object directly, however, you typically use its self-referential frames property as if it were the array-like object. The parent and top properties of a Window refer to the directly containing window and top-level ancestor window. New top-level browser windows are created with the Window.open() method. When you call this method, save the return value of the open() call in a variable and use that variable to reference the new window. The opener property of the new window is a reference back to the window that opened it. Properties In addition to the properties listed here, document content displayed within the window causes new properties to come into existence. As explained in §14.7, you can refer to an element within the document by using the value of the element’s id attribute as a property of the window (and since the window is the global object, its properties are global variables). Client-Side JavaScript Reference | 1001
Window readonly ApplicationCache applicationCache A reference to the ApplicationCache object. Cached and offline web apps can use this object to manage their cache updates. readonly any dialogArguments In Window objects created by the showModalDialog(), this property is the arguments value that was passed to showModalDialog(). In regular Window objects, this property does not exist. See §14.5 for more information. readonly Document document The Document object that describes the content of this window (see Document for details). readonly Event event [IE only] In Internet Explorer, this property refers to the Event object that describes the most recent event. In IE8 and before, the event object is not always passed to the event handler and must sometimes be accessed through this property. See Chapter 17 for further details. readonly Element frameElement If this Window is within an <iframe>, this property refers to that IFrame element. For top- level windows, this property is null. readonly Window frames This property, like the self and window properties, refers to the Window object itself. Every Window object is an array-like object of the frames contained within it. Instead of writing w[0] to refer to the first frame within a window w, this property allows you to more clearly write w.frames[0]. readonly History history The History object of this window. See History. readonly long innerHeight readonly long innerWidth The height and width, in pixels, of the document display area of this window. These properties are not supported in IE8 and before. See Example 15-9 for an example. readonly unsigned long length The number of frames contained in this window. See frames. readonly Storage localStorage This property refers to a Storage object that provides client-side storage for name/value pairs. Data stored through localStorage is visible to and shared with any documents with the same origin, and persists until deleted by the user or by a script. See also session Storage and §20.1. readonly Location location The Location object for this window. This object specifies the URL of the currently loaded document. Setting this property to a new URL string causes the browser to load and display the contents of that URL. See Location. string name The name of the window. The name is optionally specified when the window is created with the open() method or with the name attribute of a <frame> tag. The name of a window 1002 | Client-Side JavaScript Reference
Window can be used as the value of a target attribute of an <a> or <form> tag. Using the target attribute in this way specifies that the hyperlinked document or the results of form sub- mission should be displayed in the named window or frame. readonly Navigator navigator A reference to the Navigator object, which provides version and configuration informa- tion about the web browser. See Navigator. readonly Window opener A read/write reference to the Window object that contained the script that called open() to open this browser window, or null for windows that were not created in that way. This property is valid only for Window objects that represent top-level windows, not those that represent frames. The opener property is useful so that a newly created window can refer to properties and functions defined in the window that created it. readonly long outerHeight readonly long outerWidth These properties specify the total height and width, in pixels, of the browser window, including toolbars, scrollbars, window borders, and so on. These properties are not sup- ported in IE8 and before. readonly long pageXOffset Reference JavaScript Client-Side readonly long pageYOffset The number of pixels that the current document has been scrolled to the right (pageXOffset) and down (pageYOffset). These properties are not supported in IE8 and before. See Example 15-8 for an example and compatibility code that works in IE. readonly Window parent The Window object that contains this one. If this window is a top-level window, parent refers to the window itself. If this window is a frame, the parent property refers to the window or frame that contains it. string returnValue This property does not exist in normal windows, but it is defined for Windows created by showModalDialog() and has the empty string as its default value. When a dialog Win- dow is closed (see the close() method), the value of this property becomes the return value of showModalDialog(). readonly Screen screen The Screen object that specifies information about the screen: the number of available pixels and the number of available colors. See Screen for details. readonly long screenX readonly long screenY The coordinates of the upper left corner of the window on the screen. readonly Window self A reference to this window itself. This is a synonym for the window property. readonly Storage sessionStorage This property refers to a Storage object that provides client-side storage for name/value pairs. Data stored through sessionStorage is visible only to same-origin documents with- Client-Side JavaScript Reference | 1003
Window in the same top-level window or tab, and persists only for the duration of the browsing session. See also localStorage and §20.1. readonly Window top The top-level window that contains this window. If this window is a top-level window itself, the top property simply refers to the window itself. If this window is a frame, the top property refers to the top-level window that contains the frame. Contrast with the parent property. readonly object URL At the time of this writing, this property is simply a reference to a placeholder object that defines the functions documented at URL. In the future, this property may become a URL() constructor and define an API for parsing URLs and their query strings. readonly Window window The window property is identical to the self property; it contains a reference to this win- dow. Since the Window object is the global object of client-side JavaScript, this property allows us to write window to refer to the global object. Constructors As the global object for client-side JavaScript, the Window object must define all the global constructors for the client-side environment. Although they are not listed here, all of the global constructors documented in this reference section are properties of the Window object. The fact that client-side JavaScript defines Image() and XMLHttpRequest() constructors, for exam- ple, means that every Window object has properties named Image and XMLHttpRequest. Methods The Window object defines the following methods and also inherits all the global functions defined by core JavaScript (see Global in Part III). void alert(string message) The alert() method displays the specified plain-text message to the user in a dialog box. The dialog box contains an OK button the user can click to dismiss it. The dialog box is typically modal (at least for the current tab), and the call to alert() blocks until the dialog is dismissed. string atob(string atob) This utility function accepts a base64-encoded string and decodes it into a JavaScript binary string in which each character represents a single byte. Use the charCodeAt() method of the returned string to extract byte values. See also btoa(). void blur() The blur() method removes keyboard focus from the top-level browser window specified by the Window object. It is unspecified which window gains keyboard focus as a result. In some browsers and/or platforms, this method may have no effect. string btoa(string btoa) This utility function accepts a JavaScript binary string (in which each character represents a single byte) as an argument and returns the base64 encoding of it. Use String.fromChar Code() to create a binary string from an arbitrary sequence of byte values. See also atob(). 1004 | Client-Side JavaScript Reference
Window void clearInterval(long handle) clearInterval() stops the repeated execution of code that was started by a call to setInterval(). intervalId must be the value that was returned by a call to setInterval(). void clearTimeout(long handle) clearTimeout() cancels the execution of code that has been deferred with the setTimeout() method. The timeoutId argument is a value returned by the call to setTimeout() and identifies which deferred code to cancel. void close() The close() method closes the top-level browser window on which it is invoked. Scripts are generally only allowed to close windows that they opened. boolean confirm(string message) This method displays the specified question as plain text in a modal dialog box. The dialog box contains OK and Cancel buttons that the user can use to answer the question. If the user clicks the OK button, confirm() returns true. If the user clicks Cancel, confirm() returns false. void focus() This method gives keyboard focus to the browser window. On most platforms, a top-level window is brought forward to the top of the window stack so that it becomes visible when it Reference JavaScript Client-Side is given focus. CSSStyleDeclaration getComputedStyle(Element elt, [string pseudoElt]) An element in a document can obtain style information from an inline style attribute and from any number of stylesheets in the stylesheet “cascade.” Before the element can actually be displayed in a window, its style information must be extracted from the cascade, and styles specified with relative units (such as percentages or “ems”) must be “computed” to convert to pixels. These computed values are sometimes also called “used” values. This method returns a read-only CSSStyleDeclaration object that represents the CSS style values actually used to display the element. All dimensions will be in pixels. The second argument to this method is usually omitted or null, but you can also pass the CSS pseudoelement “::before” or “::after” to determine the styles used for CSS-generated content. Contrast getComputedStyle() with the style property of an HTMLElement, which gives you access only to the inline styles of an element, in whatever units they were specified, and tells you nothing about stylesheet styles that apply to the element. This method is not implemented in IE8 and before, but similar functionality is available through the nonstandard currentStyle property of each HTMLElement object. Window open([string url], [string target], [string features], [string replace]) The open() method loads and displays the specified url in a new or existing browser window or tab. The url argument specifies the URL of the document to load. If not specified, “about:blank” is used. The target argument specifies the name of the window into which the url should be loaded. If not specified, “_blank” is used. If target is “_blank”, or if there is no existing window with Client-Side JavaScript Reference | 1005
Window the specified name, a new window is created to display the contents of url. Otherwise, the url is loaded into the existing window with the specified name. The features argument used to specify the window position, size, and features (such as menubar, toolbar, etc.). In modern browsers that support tabs, it is often ignored, and it is not documented here. When you use Window.open() to load a new document into an existing window, the replace argument specifies whether the new document has its own entry in the window’s browsing history or whether it replaces the history entry of the current document. If replace is true, the new document replaces the old. If this argument is false or is not specified, the new document has its own entry in the Window’s browsing history. This argument provides func- tionality much like that of the Location.replace() method. void postMessage(any message, string targetOrigin, [MessagePort[] ports]) Send a copy of the specified message and the optionally specified ports to this window, but only if the document displayed in this window has the specified targetOrigin. message can be any object that can be cloned with the structured clone algorithm (see “Struc- tured Clones” on page 672). targetOrigin should be an absolute URL that specifies the scheme, host, and port of the desired origin. Or targetOrigin can be “*” if any origin is ac- ceptable or “/” to use the script’s own origin. Calling this method on a window causes a message event on that window. See MessageEvent and §22.3. void print() Calling print() causes the browser to behave as if the user had selected the browser’s Print button or menu item. Usually, this brings up a dialog box that enables the user to cancel or customize the print request. string prompt(string message, [string default]) The prompt() method displays the specified message in a modal dialog box that also contains a text input field and OK and Cancel buttons and blocks until the user clicks one of the buttons. If the user clicks the Cancel button, prompt() returns null. If the user clicks the OK button, prompt() returns the text currently displayed in the input field. The default argument specifies the initial value of the text input field void scroll(long x, long y) This method is a synonym for scrollTo(). void scrollBy(long x, long y) scrollBy() scrolls the document displayed in window by the relative amounts specified by dx and dy. void scrollTo(long x, long y) scrollTo() scrolls the document displayed within window so the point in the document speci- fied by the x and y coordinates is displayed in the upper left corner, if possible. 1006 | Client-Side JavaScript Reference
Window long setInterval(function f, unsigned long interval, any args...) setInterval() registers the function f to be invoked after interval milliseconds and then to be repeatedly invoked at that specified interval. f will be invoked with the Window as its this value, and will be passed any additional args that were passed to setInterval(). setInterval() returns a number that can later be passed to Window.clearInterval() to cancel the execution of code. For historical reasons, f may be a string of JavaScript code instead of a function. If so, the string will be evaluated (as if it were a <script>) every interval milliseconds. Use setTimeout() when you want to defer the execution of code but do not want it to be repeatedly executed. long setTimeout(function f, unsigned long timeout, any args...) setTimeout() is like setInterval(), except that it invokes the specified function only once: it registers f to be invoked after timeout milliseconds have been elapsed and returns a number that can later be passed to clearTimeout() to cancel the pending invocation. When the speci- fied time has passed, f will be invoked as a method of the Window and will be passed any specified args. If f is a string rather than a function, it will be executed after timeout millisec- onds as if it were a <script>. Reference JavaScript Client-Side any showModalDialog(string url, [any arguments]) This method creates a new Window object, sets its dialogArguments property to arguments, loads url into the window, and blocks until the window is closed. Once closed, it returns the returnValue property of the window. See §14.5 and Example 14-4 for a discussion and example. Event Handlers Most events that occur on HTML elements bubble up the document tree, to the Document object and then on to the Window object. For this reason, you can use all of the event handler properties listed in Element on Window objects. And in addition, you can use the event handler properties listed below. For historical reasons, each of the event handler properties listed here can also be defined (as an HTML attribute or as a JavaScript property) on the <body> element. Event Handler Invoked... onafterprint After the window’s contents are printed onbefore Before the window’s contents are printed print onbe Before navigating away from the current page. If the return value is a string, or if the handler sets the foreunload returnValue property of its event object to a string, that string will be displayed in a confirmation dialog. See BeforeUnloadEvent. onblur When the window loses keyboard focus onerror When a JavaScript error occurs. This is not an ordinary event handler. See §14.6. onfocus When the window gains keyboard focus onhashchange When the fragment identifier (see Location.hash) of the document changes as the result of history navigation (see HashChangeEvent) Client-Side JavaScript Reference | 1007
Worker Event Handler Invoked... onload When the document and its external resources are fully loaded onmessage When a script in another window sends a message by calling the postMessage() method. See Mes- sageEvent. onoffline When the browser loses its connection to the Internet ononline When the browser regains a connection to the Internet onpagehide When the page is about to be cached and replaced by another page onpageshow When a page is first loaded, a pageshow event is fired right after the load event, and the event object has a persisted property of false. When a previously loaded page is restored from the browser’s in- memory cache, however, no load event is fired (since the cached page is already in its loaded state) and a pageshow event is fired with an event object that has its persisted property set to true. See Page- TransitionEvent. onpopstate When the browser loads a new page or restores a state saved with History.pushState() or History.replaceState(). See PopStateEvent. onresize When the user changes the size of the browser window onscroll When the user scrolls the browser window onstorage Content of localStorage or sessionStorage changes. See StorageEvent. onunload The browser navigates away from a page. Note that if you register an onunload handler for a page, that page will not be cacheable. To allow users to quickly return to your page without reloading, use onpagehide instead. Worker a worker thread EventTarget A Worker represents a background thread. Create a new Worker with the Worker() con- structor, passing the URL of a file of JavaScript code for it to run. The JavaScript code in that file can use synchronous APIs or perform compute-intensive tasks without freezing up the main UI thread. Workers run their code in a completely separate execution context (see WorkerGlobalScope), and the only way to exchange data with a worker is via asynchronous events. Call postMessage() to send data to the Worker, and handle message events to receive data from the worker. See §22.4 for an introduction to worker threads. Constructor new Worker(string scriptURL) Constructs a new Worker object and causes it to run the JavaScript code in scriptURL. Methods void postMessage(any message, [MessagePort[] ports]) Send message to the worker, which will receive it as a MessageEvent object sent to its onmessage handler. message can be a JavaScript primitive value or object or array, but not a 1008 | Client-Side JavaScript Reference
WorkerGlobalScope function. Client-side types ArrayBuffer, File, Blob, and ImageData are allowed, but Nodes, such as Document and Element, are not allowed (see “Structured Clones” on page 672 for details). The optional ports argument is an advanced feature that allows you to pass one or more direct communication channels to the Worker. If you create two Worker objects, for example, you can allow them to communicate directly with each other by passing them each one end of a MessageChannel. void terminate() Stop the worker and abort the script it is running. Event Handlers Because workers run code in a completely separate execution environment than the one that created them, the only way they can communicate with their parent thread is by events. You can register event handlers on these properties or use the EventTarget methods. onerror When an exception is thrown in the script being run by a Worker, and that error is not handled by the onerror handler of the WorkerGlobalScope, the error triggers an error event on the Worker object. The event object associated with this event is a Reference JavaScript Client-Side ErrorEvent. The error event does not bubble. If this worker is owned by another worker, canceling an error event prevents it from being propagated up to the parent worker. If this Worker object is already in the main thread, canceling the event may prevent it from being displayed in the JavaScript console. onmessage When the script that the worker is running calls its global postMessage() function (see WorkerGlobalScope), a message event is triggered on the Worker object. The object passed to the event handler is a MessageEvent, and its data property contains a clone of the value that the worker script passed to postMessage(). WorkerGlobalScope EventTarget, Global A Worker thread runs in a completely different execution environment than the parent thread that spawned it. The global object for a worker is a WorkerGlobalScope object, so this page describes the execution environment “inside” a Worker. Since WorkerGlobalScope is a global object, it inherits the Global object of core JavaScript. Properties In addition to the properties listed here, WorkerGlobalScope also defines all of the core Java- Script global properties, such as Math and JSON. readonly WorkerLocation location This property is like the window.location Location object: it allows a worker to inspect the URL it was loaded from and includes properties that return individual portions of the URL. Client-Side JavaScript Reference | 1009
WorkerGlobalScope readonly WorkerNavigator navigator This property is like the window.navigator Navigator object: it defines properties that allow a worker to determine what browser it is running in and whether it is currently online or not. readonly WorkerGlobalScope self This self-referential property refers to the WorkerGlobalScope global object itself. It is like the window property of the Window object in the main thread. Methods In addition to the properties listed here, WorkerGlobalScope also defines all of the core Java- Script global functions, such as isNaN() and eval(). void clearInterval(long handle) This method is just like the Window method of the same name. void clearTimeout(long handle) This method is just like the Window method of the same name. void close() This method puts the worker into a special “closing” state. Once in this state, it will not fire any timers or trigger any events. The script continues running until it returns to the worker’s event loop, at which point the worker stops. void importScripts(string urls...) For each of the specified urls, this method resolves the URL relative to the worker’s location, then loads the content of the URL, and then executes that content as JavaScript code. Note that this is a synchronous method. It loads and executes each file in turn and does not return until all scripts have executed. (If any script throws an exception, however, that exception will propagate and prevent any subsequent URLs from being loaded and executed.) void postMessage(any message, [MessagePort[] ports]) Sends a message (and optionally an array of ports) to the thread that spawned this worker. Calling this method causes a message event to be triggered on the Worker object in the parent thread, and the associated MessageEvent object will include a clone of message as its data property. Note that in a worker, postMessage() is a global function. long setInterval(any handler, [any timeout], any args...) This method is just like the Window method of the same name. long setTimeout(any handler, [any timeout], any args...) This method is just like the Window method of the same name. Constructors WorkerGlobalScope includes all of the core JavaScript constructors, such as Array(), Date(), and RegExp(). It also defines key client-side constructors for XMLHttpRequest, FileReaderSync, and even the Worker object itself. 1010 | Client-Side JavaScript Reference
WorkerLocation Event Handlers You can register event handlers for workers by setting these global event handler properties, or you can use the EventTarget methods implemented by WorkerGlobalScope. onerror This is not a normal event handler: it is like the onerror property of Window rather than the onerror property of Worker. When an unhandled exception occurs in the worker, this function, if defined, will be invoked with three string arguments that specify an error message, a script URL, and a line number. If the function returns false, the error is considered handled and does not propagate. Otherwise, if this property is not set, or if the error handler does not return false, the error propagates and causes an error event on the Worker object in the parent thread. onmessage When the parent thread calls the postMessage() method of the Worker object that rep- resents this worker, it causes a message event to be triggered on this WorkerGlobalScope. This event handler function will be passed a MessageEvent object, and the data property of that object will hold a clone of the message argument sent by the parent thread. WorkerLocation Reference JavaScript Client-Side the URL of a worker’s main script The WorkerLocation object referenced by the location property of a WorkerGlobalScope is like the Location object referenced by the location property of a Window: it represents the URL of the worker’s main script and defines properties that represent portions of that URL. Workers differ from Windows in that they cannot be navigated or reloaded, so the properties of a WorkerLocation object are read-only, and the object does not implement the methods of the Location object. The WorkerLocation object does not automatically convert to a string the way a regular location object does. In a worker, you cannot simply write location when you mean location.href. Properties These properties have the same meanings as the same-named properties of the Location object. readonly string hash The fragment identifier portion of the URL, including the leading hash mark. readonly string host The host and port portions of the URL. readonly string hostname The host portion of the URL. Client-Side JavaScript Reference | 1011
WorkerNavigator readonly string href The complete text of the URL that was passed to the Worker() constructor. This is the only value that the worker receives directly from its parent thread: all other values are received indirectly through message events. readonly string pathname The pathname portion of the URL. readonly string port The port portion of the URL. readonly string protocol The protocol portion of the URL. readonly string search The search or query portion of the URL, including the leading question mark. WorkerNavigator browser information for workers The navigator property of a WorkerGlobalScope refers to a WorkerNavigator object that is a simplified version of the Navigator object of a Window. Properties Each of these properties has the same meaning that it does in the Navigator object. readonly string appName See the appName property of Navigator. readonly string appVersion See the appVersions property of Navigator. readonly boolean onLine true if the browser is online and false if it is not. readonly string platform A string that identifies the operating system and/or hardware platform on which the browser is running. readonly string userAgent The value the browser uses for the user-agent header in HTTP requests. XMLHttpRequest An HTTP request and response EventTarget The XMLHttpRequest object allows client-side JavaScript to issue HTTP requests and receive responses (which need not be XML) from web servers. XMLHttpRequest is the subject of Chapter 18, and that chapter contains many examples of its use. 1012 | Client-Side JavaScript Reference
XMLHttpRequest Create an XMLHttpRequest object with the XMLHttpRequest() constructor (see the sidebar in §18.1 for information on how to create an XMLHttpRequest object in IE6) and then use it like this: 1. Call open() to specify the URL and method (usually “GET” or “POST”) for the request. 2. Set the onreadystatechange property to the function that will be notified of the progress of the request. 3. Call setRequestHeader(), if needed, to specify additional request parameters. 4. Call send() to send the request to the web server. If it is a POST request, you can also pass a request body to this method. Your onreadystatechange event handler function will be invoked as the request proceeds. When readyState is 4, the response is complete. 5. When readyState is 4, check the status code to ensure that the request was successful. If so, use getResponseHeader() or getResponseHeaders() to retrieve values from the re- sponse header, and use the responseText or responseXML properties to obtain the response body. XMLHttpRequest defines a relatively high-level interface to the HTTP protocol. It takes care of details such as handling redirects, managing cookies, and negotiating cross-origin connec- tions with CORS headers. The XMLHttpRequest features described above are well supported by all modern browsers. Reference JavaScript Client-Side At the time of this writing, an XMLHttpRequest Level 2 standard is under development and browsers are beginning to implement it. The properties, methods, and event handlers listed below include XMLHttpRequest Level 2 features, which may not yet be implemented by all browsers. These newer features are marked “XHR2.” Constructor new XMLHttpRequest() This no-argument constructor returns a new XMLHttpRequest object. Constants These constants define the values of the readyState property. Prior to XHR2, these constants are not widely defined, and most code uses integer literals rather than these symbolic values. unsigned short UNSENT = 0 This is the initial state. The XMLHttpRequest object has just been created or has been reset with the abort() method. unsigned short OPENED = 1 The open() method has been called, but send() has not. The request has not yet been sent. unsigned short HEADERS_RECEIVED = 2 The send() method has been called, and the response headers have been received, but the response body has not yet been received. unsigned short LOADING = 3 The response body is being received but is not complete. Client-Side JavaScript Reference | 1013
XMLHttpRequest unsigned short DONE = 4 The HTTP response has been fully received or has stopped because of an error. Properties readonly unsigned short readyState The state of the HTTP request and the server’s response. The value of this property begins at 0 when an XMLHttpRequest is first created and increases to 4 when the complete HTTP response has been received. The constants listed above define the possible values. The value of readyState never decreases, unless abort() or open() is called on a request that is already in progress. In theory, a readystatechange event is dispatched every time the value of this property changes. In practice, however, an event is only really guaranteed when readyState changes to 4. (The XHR2 progress events provide a more reliable way of tracking the progress of a request.) readonly any response In XHR2, this property holds the server’s response. Its type depends on the response Type property. If responseType is the empty string or “text”, property will hold the re- sponse body as a string. If responseType is “document”, this property will be a parsed representation of the response body as an XML or HTTP Document. If responseType is “arraybuffer”, this property will be an ArrayBuffer that represents the bytes of the re- sponse body. And if responseType is “blob”, this property will be a Blob that represents the bytes of the response body. readonly string responseText If readyState is less than 3, this property is the empty string. When readyState is 3, this property returns whatever portion of the response has been received so far. If ready State is 4, this property holds the complete body of the response. If the response includes headers that specify a character encoding for the body, that encoding is used. Otherwise, the Unicode UTF-8 encoding is assumed. string responseType In XHR2, this property specifies the desired response type and determines the type of the response property. The legal values are “text”, “document”, “arraybuffer”, and “blob”. The default is the empty string, which is a synonym for “text”. If you set this property, the responseText and responseXML properties will raise exceptions and you must use the XHR2 response property to get the server’s response. readonly Document responseXML The response to the request, parsed as an XML or HTML Document object, or null if the response body is not ready or is not a valid XML or HTML document. readonly unsigned short status The HTTP status code returned by the server, such as 200 for success, 404 for “Not Found” errors, or 0 if the server has not set a status code yet. 1014 | Client-Side JavaScript Reference
XMLHttpRequest readonly string statusText This property specifies the HTTP status code of the request by name rather than by number. That is, it is “OK” when status is 200 and “Not Found” when status is 404. This property is the empty string if the server has not set a status code yet. unsigned long timeout This XHR2 property specifies a timeout value in milliseconds. If the HTTP request takes longer than this to complete, it will be aborted and timeout event will be triggered. You can only set this property after calling open() and before calling send(). readonly XMLHttpRequestUpload upload This XHR2 property refers to an XMLHttpRequestUpload object that defines a set of event handler registration properties for monitoring the progress of the HTTP request body upload. boolean withCredentials This XHR2 property specifies whether authentication credentials should be included in CORS requests and whether cookie headers in CORS responses should be processed. The default value is false. Methods Reference JavaScript Client-Side void abort() This method resets the XMLHttpRequest object to a readyState of 0 and aborts any pending network activity. You might call this method, for example, if a request has taken too long, and the response is no longer necessary. string getAllResponseHeaders() This method returns the HTTP response headers (with cookie and CORS headers filtered out) sent by the server, or null if the headers have not been received yet. The headers are returned as a single string, with one header per line. string getResponseHeader(string header) Returns the value of a named HTTP response header, or null if headers have not been received yet or if the response does not include the specified header. Cookie and CORS-related headers are filtered out and cannot be queried. If the response includes more than one header with the specified name, the returned string will include the value of all of those headers, con- catenated and separated by a comma and a space. void open(string method, string url, [boolean async, string user, string pass]) This method resets the XMLHttpRequest object and stores its arguments for later use by the send(). method is the HTTP method to be used for the request. Reliably implemented values include GET, POST, and HEAD. Implementations may also support the CONNECT, DELETE, OPTIONS, PUT, TRACE, and TRACK methods. url is the URL being requested. Relative URLs are resolved in the normal way, using the URL of the document that contains the script. The same-origin security policy (see §13.6.2) Client-Side JavaScript Reference | 1015
XMLHttpRequest requires that this URL have the same hostname and port as the document that contains the script making the request. XHR2 allows cross-origin requests to servers that support CORS. If the async argument is specified and is false, the request is performed synchronously and the send() method will block until the response is complete. This is not recommended except when XMLHttpRequest is used in a Worker. The optional user and pass arguments specify a username and password to use with the HTTP request. void overrideMimeType(string mime) This method specifies that the server’s response should be interpreted according to the speci- fied mime type (and charset parameter, if that is included) instead of using the Content-Type header of the response. void send(any body) This method causes an HTTP request to be issued. If there has been no previous call to open(), or, more generally, if readyState is not 1, send() throws an exception. Otherwise, it issues an HTTP request that consists of: • The HTTP method, URL, and authorization credentials (if any) specified in the previous call to open(). • The request headers, if any, specified by previous calls to setRequestHeader(). • The body argument passed to this method. The body may be a string or a Document object that specifies the request body, or may be omitted or null if the request has no body (such as GET requests that never have a body). In XHR2, the body may also be an ArrayBuff- er, a Blob, or a FormData object. If the async argument to the previous call to open() was false, this method blocks and does not return until readyState is 4 and the server’s response has been fully received. Otherwise, send() returns immediately, and the server’s response is processed asynchronously with no- tifications provided through event handlers. void setRequestHeader(string name, string value) setRequestHeader() specifies an HTTP request header name and value that should be included in the request issued by a subsequent call to send(). This method may be called only when readyState is 1—i.e., after a call to open(), but before a call to send(). If a header with the specified name has already been specified, the new value for that header is the previously specified value, plus a comma, a space, and the value specified in this call. If the call to open() specifies authorization credentials, XMLHttpRequest automatically sends an appropriate Authorization request header. You can also append to this header yourself with setRequestHeader(), however. XMLHttpRequest automatically sets “Content-Length”, “Date”, “Referer”, and “User- Agent” and does not allow you to spoof them. There are a number of other headers, including cookie-related headers, that you cannot set with this method. The complete list is in §18.1. 1016 | Client-Side JavaScript Reference
XMLHttpRequestUpload Event Handlers The original XMLHttpRequest object defined only a single event handler property: onreadystatechange. XHR2 expands the list with a set of progress event handlers that are much easier to use. You can register handlers by setting these properties or by using the methods of EventTarget. XMLHttpRequest events are always dispatched on the XMLHttpRequest ob- ject itself. They do not bubble and have no default action to cancel. readystatechange events have an associated Event object, and all of the other event types have an associated ProgressEvent object. See the upload property and XMLHttpRequestUpload for a list of events you can use to monitor the progress of HTTP uploads. onabort Triggered when a request is aborted. onerror Triggered if the request fails with an error. Note that HTTP status codes such as 404 do not constitute an error since the response still completes successfully. A DNS failure while trying to resolve the URL or an infinite loop of redirects would both cause this event to occur, however. onload Reference JavaScript Client-Side Triggered when the request completes successfully. onloadend Triggered when the request has succeeded or failed after the load, abort, error, or timeout event. onloadstart Triggered when the request starts. onprogress Triggered repeatedly (approximately every 50ms) while the response body is downloading. onreadystatechange Triggered when the readyState property changes, most importantly when the response is complete. ontimeout Triggered if the time specified by the timeout property has elapsed and the response is not complete. XMLHttpRequestUpload EventTarget An XMLHttpRequestUpload object defines a set of event handler registration properties for monitoring the progress of an HTTP request body upload. In browsers that implement the XMLHttpRequest Level 2 specification, each XMLHttpRequest object has an upload property that refers to an object of this type. To monitor the progress of the request upload, simply set Client-Side JavaScript Reference | 1017
XMLHttpRequestUpload these properties to appropriate event handler functions or call the EventTarget methods. Note that the upload progress event handlers defined here are exactly the same as the download progress event handlers defined on XMLHttpRequest itself, except that there is no onreadystatechange property on this object. Event Handlers onabort Triggered if the upload is aborted. onerror Triggered if the upload fails with a network error. onload Triggered when the upload succeeds onloadend Triggered when the upload finishes, whether successfully or not. A loadend event will always follow a load, abort, error, or timeout event. onloadstart Triggered when the upload starts. onprogress Triggered repeatedly (approximately every 50ms) while the upload is occurring. ontimeout Triggered if the upload is aborted because the XMLHttpRequest timeout expired. 1018 | Client-Side JavaScript Reference
Index Symbols multiplication operator, 33, 62 wildcard character in E4X, 285 3D graphics for <canvas> element, 631, 688 @ (at sign) & (ampersand) @if, @else, and @end keywords in && (logical AND) operator, 41, 62, 75 conditional comments, 331 short-circuiting behavior of, 123 in attribute names, 285 &= (bitwise AND and assignment) \ (backslash) operator, 62, 78 breaking multiline string literals, 37 bitwise AND operator, 62, 69 escape sequences in string literals, 37 < > (angle brackets) escaping special characters in regular < (less than) operator, 62, 73 expressions, 253 substituting compareTo ( ) method, 223 ^ (caret) << (bitwise left shift) operator, 62, 70 beginning-of-string matching in regular <<= (bitwise left shift and assignment) expressions, 258 operator, 62, 78 bitwise XOR operator, 62, 70 <= (less than or equal to) operator, 62, 73 negating character classes in regular substituting compareTo( ) method, 223 expressions, 253 > (greater than) operator, 62, 73 ^= (bitwise XOR and assignment) operator, substituting compareTo( ) method, 223 62, 78 >= (greater than or equal to) operator, 62, , (comma) operator, 85 73 { } (curly braces) substituting compareTo( ) method, 223 around function body, omitting in >> (bitwise right shift with sign extension) shorthand functions, 282 operator, 62, 70 enclosing object initializer expressions, 59 >>= (bitwise right shift with sign extension enclosing statement blocks, 88 and assignment) operator, 62, 78 escape characters in XML literal syntax of >>> (bitwise right shift with zero fill) E4X, 284 operator, 62, 70 in function definitions, 164 >>>= (bitwise right shift with zero fill and initializer expressions in, 5 assignment) operator, 62, 78 $ (dollar sign) * (asterisk) $$( ) method, ConsoleCommandLine, 884 *= (multiplication and assignment) $( ) function, 11, 524, 525–528 operator, 62, 78 looking up elements by ID, 352 matching zero or more occurrences in using instead of querySelectorAll( ), 529 regular expressions, 254 $( ) method, ConsoleCommandLine, 884 We’d like to hear your suggestions for improving our indexes. Send email to index@oreilly.com. 1019
$0 and $1 properties, subtraction operator, 33, 62 ConsoleCommandLine, 884 unary minus operator, 68 $1, $2 … $n variables in regular expressions, ( ) (parentheses) 260 enclosing expressions in if statements, 92 end-of-string matching in regular grouping in regular expressions, 256 expressions, 252, 258 in function and method invocations, 61 . (dot) in function definitions, 59, 164 . . (descendant) operator, 285 in generator expressions, 282 dot operator, 5 in object creation expressions, 61 property access in method invocations, statements beginning with (, 26 168 % (percent sign) property access with, secure subsets and, %= (modulus and assignment) operator, 62, 268 78 querying and setting properties, 120 modulus operator, 33, 62 matching any character except newlines in . (period) (see . (dot)) regular expressions, 254 + (plus sign) in property access expressions, 60 ++ (increment) operator, 62, 68 = (equals sign) line breaks in statements and, 27 == (equality) operator, 62, 71 side effects, 64, 88 NaN values and, 34 += (addition and assignment) operator, 62, object-to-primitive conversions, 51 78 substituting compareTo( ) method, 223 appending text to innerHTML property, == and === operators 379 comparing null and undefined values, addition and string concatenation 42 operators, 67 comparing primitive values and wrapper object-to-primitive conversions, 51 objects, 44 addition operator, 33, 62 type conversions and equality, 47 matching one or more occurrences in regular === (strict equality) operator, 62, 71 expressions, 254 =? in URL or data string passed to statements beginning with, 26 jQuery.getJSON( ), 563 string concatenation operator, 62 assignment operator, 62 unary plus operator, 68 ! (exclamation mark) ? (question mark) != (inequality) operator, 62, 71 ?! (negative lookahead assertion) in regular NaN comparisons, 34 expressions, 258 substituting compareTo( ) method, 223 ?: (conditional) operator, 62, 82 !== (strict inequality) operator, 62, 71 ?= (positive lookahead assertions) in regular comparing variable to null, 40 expressions, 258 testing for undefined properties, 125 nongreedy repetition in regular expressions, logical NOT operator, 48, 62, 77 255 - (minus sign) \" \" (quotation marks, double) enclosing string -- (decrement) operator, 62, 69 literals, 36 line breaks in statements and, 27 quoting in stylesheet or style attribute side effects, 64, 88 strings, 432 -= (subtraction and assignment) operator, ' ' (quotation marks, single) enclosing string 78 literals, 36 -Infinity (negative infinity), 33 single-quoted HTML attribute, JavaScript negation operator, 62 code in, 317 statements beginning with, 26 ; (semicolon) 1020 | Index
ending statements, 6, 87 having name attribute rather than href optional, ending statements, 25 attribute, 367 placing outside of style attribute or href attribute, 315, 367 stylesheet strings, 432 abort( ) method separating name-value pairs in style FileReader object, 925 properties, 414 XMLHttpRequest object, 507, 510 statement blocks and, 89 about:blank URL, 354 / (slash) abs( ) function, Math object, 791 /* */ comments in javascript: URL code, absolute positioning of elements, 420 315 abstract classes, 228 /*@cc_on and @*/in conditional class hierarchies and, 234–238 comments, 331 abstract methods, 228 // and /” */ in comments, 23 accept property, Input object, 942 // in comments, 4 acceptCharset property, Form object, 928 /= (division and assignment) operator, 62, Access-Control-Allow-Origin response header, 78 335 division operator, 33, 62 accessibility, 332 enclosing regular expression literals, 251 accessor properties, 129, 815 statements beginning with, 26 adding to existing objects, 131 [ ] (square brackets) defining using object literal syntax, 129 accessing array elements, 143 inheritance and, 123 accessing individual string characters, 160 legacy API for, 134 accessing values in multidimensional arrays, property descriptor, 131 148 uses of, 130 array operator, 5, 688 accuracy property, Geocoordinates, 933 accessing individual string characters, acos( ) function, Math object, 791 39 action property, Form object, 399, 928 creating arrays, 141 activeElement property, Document, 892 enclosing array comprehensions, 281 ActiveX controls, scripting, 336 enclosing array initializers, 58 add( ) method enclosing character classes in regular DOMTokenList object, 438, 902 expressions, 253 HTMLOptionsCollection object, 938 in property access expressions, 60, 168 jQuery, 580 restriction in secure subsets, 268 Select element, 987 querying and setting properties, 120, 121 addClass( ) method, jQuery, 532 statements beginning with [, 26 addColorStop( ), CanvasGradient object, 647, ~ (tilde), bitwise NOT operator, 62, 70 866 _ (underscore), in function names, 165 addElement( ), DataTransfer object, 476, 889 | (vertical bar) addEventListener( ) method, 321, 457 alternation in regular expression pattern capturing event handlers, 463 matching, 256 EventTarget object, 922 bitwise OR operator, 62, 70 incompatibilities between attachEvent( ) |= (bitwise OR and assignment) operator, and, 328 62, 78 not implemented by Internet Explorer, 325 || (logical OR) operator, 62, 76, 171 registering event handlers, 458 Worker object, 681 A WorkerGlobalScope object, 683 <a> elements adoptNode( ) method, Document object, 894 ADsafe security subset, 268 Index | 1021
affine transforms, 640 CSS Transitions and Animations, 419 after( ) method, jQuery, 538 jQuery methods for, 956 Ajax API-specific events, 449 defined, 491 apostrophes, 37 functions in jQuery, 958 (see also ‘ ’ (quotation marks, single), under in jQuery 1.5, 565 Symbols) transport mechanisms for, 492 escaping in single-quoted strings, 37 utilities in jQuery, 559–571 append( ) method ajax( ) function, 564–569 BlobBuilder object, 695, 864 data types, 563 FormData object, 932 get( ) and post( ) functions, 563 jQuery, 538 getJSON( ) function, 561 appendChild( ), Node object, 383, 977 getScript( ) function, 561 appendData( ) method load( ) method, 559 Comment node, 881 passing data to, 562 Text node, 993 XML with, 493 appendTo( ) method, jQuery, 538 ajax( ) function, 564–569 Apple iPhone and iPad devices, gesture and callbacks, 567 touch events, 456 common options, 565 <applet> elements, 537 uncommon options and hooks, 568 application cache, 601–607 ajaxSetup( ) function, 565 creating application manifest file, 601 alert( ) method, Window object, 308, 348, status property values, 606 1004 updates, 603–607 alpha values ApplicationCache object, 859 specifying in canvas, 645 constants, values for status property, 859 transparency of a color, 427 event handlers, 860 altitude property, Geocoordinates object, 933 status property, 606 altitudeAccuracy, Geocoordinates object, 933 swapCache( ) method, 860 altKey property, 467, 485 update( ) method, 860 Event object, 915 applicationCache property, Window object, mouse events, 451 604, 1002 anchors (regular expression), 258 apply( ) and call( ), Function object, 170, 187 anchors property, HTMLDocument, 367 restrictions in secure subsets, 267 andSelf( ) method, jQuery, 582 apply( ) method, Function object, 776 angles, specifying in radians in canvas, 627, appName property 638 Navigator object, 347, 974 animate( ) method, jQuery, 551, 552 WorkerNavigator object, 1012 animation options object, 555 appVersion property animation properties object, 554 Navigator object, 347, 974 custom animations with, 553 WorkerNavigator object, 1012 animations arc( ), CanvasRenderingContext2D, 631, 643, client-side libraries supporting, 435 873 creating using inline scripting of CSS, 433– arcTo( ), CanvasRenderingContext2D, 643, 435 873 creating using jQuery, 551–558 arguments (function), 171 canceling, delaying, and queuing effects, object properties as, 174 557 variable-length argument lists, 172 custom animations, 553–557 Arguments object, 172, 720 simple effects, 552 callee and caller properties, 173 1022 | Index
callee property, 720 reduce( ) and reduceRight( ), 155 length property, 186, 721 reduce( ) method, 732 restriction in secure subsets, 267 reduceRight( ) method, 733 arguments property, Function object, 777 reverse( ) method, 149, 734 arguments[ ] array, 719 shift( ) method, 734 arithmetic expressions, 66–70 slice( ) method, 150, 735 + operator, 67 some( ) method, 155, 736 bitwise operators, 69 sort( ) method, 149, 224, 737 unary arithmetic operators, 68 splice( ) method, 151, 737 arithmetic operators, 33, 62 toLocaleString( ) method, 738 arity (functions), 173, 186 toString( ) and toLocaleString( ), 152 array comprehensions, 280 toString( ) method, 739 changing to generator expressions, 282 unshift( ) and shift( ) methods, 152 syntax, 281 unshift( ) method, 739 Array( ) constructor, 142 of class instances, sorting, 224 array-like objects, 158–160, 353 comparing, 45 Arguments object, 172 conversions, 51 DOMTokenList object, 438 to strings, 152 frames property referring to, 357 converting jQuery object to true array, 529 HTMLCollection objects, 367 creating, 141 jQuery, 528 distinguishing from non-array objects, 157 typed arrays, 687 ES5 Array methods, 328, 529 ArrayBuffer object, 689, 861 functions assigned to elements, 176 byte ordering endianness, 690 initializers, 58 readAsArrayBuffer( ), FileReader, 698, 699 iterating, 146–148 ArrayBufferView object, 861 with for/each loops, 274 arrays, 5, 29, 141–161 with for/in loops, 100 adding and deleting elements, 145 with jQuery.each( ) method, 572 Array class, 30 Java, getting and setting elements with indexOf( ) and lastIndexOf( ), 157 JavaScript in Rhino, 292 toString( ) method, 50 length of, 145 Array object, 722–740 methods, 148–152 concat( ) method, 150, 724 ECMAScript 5, 153–157 every( ) method, 154, 725 multidimensional, 148 filter( ) method, 154, 726 objects as associative arrays, 120 forEach( ) method, 153, 726 processing with functions, 192–193 indexOf( ) method, 727 property access expressions, 60 isArray( ) method, 160 reading and writing elements, 143 join( ) method, 149, 728 sparse, 144 lastIndexOf( ) method, 729 strings as, 39, 160 length property, 722, 730 typed, 996 map( ) method, 154, 730 typed, and ArrayBuffers, 687–691 methods, 722 ArrayBuffers, 689 methods, invoking indirectly on efficiency of typed arrays, 688 NodeLists or kinds of typed arrays, 687 HTMLCollections, 367 set( ) method, 689 pop( ) method, 731 subarray( ) method, 689 push( ) and pop( ) methods, 151 of values, destructuring assignments, 272 push( ) method, 731 asin( ) function, Math object, 792 Index | 1023
assert( ) method, Console object, 882 getting and setting HTML attributes with assign( ) method, Location object, 344, 965 jQuery, 531 assignment getting and setting non-HTML attributes, destructuring, 272, 277 376 object properties, 122 HTML attributes affecting audio and video properties, 122 playback, 618 rules for success or failure of, 123 HTML attributes mirrored by event handler assignment expressions, 77 properties, 315 assignment with operation, 78 HTML elements, 910–913 side effects, 88 HTML, as element properties, 375 assignment operators, 62 object, 116, 135–138 side effects, 64 class attribute, 136 assistive technology, 332 extensible attribute, 137 animation interfering with, 551 property attributes, 116, 131–134 associative arrays, 120 copying, 133 associativity, operator, 65 querying and setting, 131 async property, Script object, 985 setting for event handlers, 457 asynchronous I/O attributes property, Element object, 903 scripting with Node, 296–304 audio and video HTTP client utilities module (example), MediaElement superclass, 965–970 302–304 MediaError objects, 970 HTTP server (example), 300–302 scripting, 615 XMLHttpRequest and File API controlling playback, 617 specifications, Version 2, 455 media events, 620 asynchronous loading and execution of scripts, querying media status, 618 319 type selection and loading, 617 asynchronous messaging between scripts of Video object, 998 different origins, 677 <audio> elements, 615 atan( ) function, Math object, 792 controls attribute, 616 atan2( ) function, Math object, 792 events, 454 atob( ) method, Window object, 1004 Audio object, 862 attachEvent( ) method, 321, 457, 923 audio property, Video object, 998 handlers registered with, this value, 461 Audio( ) constructor, 616 incompatibilities between Authorization headers, 497 addEventListener( ) and, 328 autocomplete property registering event handlers in IE, 459 Form object, 928 attention, drawing to elements of a document, Input object, 942 437 autofocus property, FormControl object, 930 Attr object, 378, 862 autoplay property, MediaElement object, 618, attr( ) method, jQuery, 531, 542 966 attribute names in E4X, 285 availHeight property, Screen object, 984 attributes, 375–378 availWidth property, Screen object, 984 as Attr nodes, 378 CSS attribute names for animation B properties object, 554 dataset, 377 \b (backspace character) in regular expressions, event handlers registered as, scope, 461 254 getting and setting CSS attributes with back( ) method, History object, 345, 936 jQuery, 532 background CSS style property, 419 background, CSS style properties for, 427 1024 | Index
background-color property, 421, 426 event handler registration with jQuery, 541 baseURL property, Node object, 976 blur( ) method before( ) method, jQuery, 538 Element object, 906 BeforeUnloadEvent object, 862 Window object, 1004 beginPath( ), CanvasRenderingContext2D, <body> elements, event handlers in, 458 632, 873 body property Bezier curves Document object, 892 drawing in canvas, 643–645 HTMLDocument object, 367 quadraticCurveTo( ) method, 878 bookmarklets bezierCurveTo( ), for currently selected text, 408 CanvasRenderingContext2D, 643, using javascript: URLs for, 316 874 Boolean object, 740 big-endian byte ordering, 690, 890 toString( ) method, 741 binary data valueOf( ) method, 741 Blobs and APIs that use them, 691 Boolean( ) constructor, 43 in HTTP responses, 501 Boolean( ) function, type conversions with, 47 binary floating-point numbers, 35 booleans, 29 Binary Large Objects (see Blobs) boolean values, 40 bind( ) method, 188 conversions, 45 event handler registration in jQuery, 544 object-to-boolean conversions, 49 Function object, 208, 778 wrapper objects, 43 similarity of jQuery.proxy( ) function, border property, 416 573 borders Function.bind( ) method for ECMAScript 3, in CSS box model, 424 189 specifying color of element’s border, 426 live events and, 549 specifying in CSS, 423 partial application of functions, 194 borrowing methods, 224 bitwise operators, 62, 69 bottom and right style properties, 421, 425 _blank window name, 354 bottom property, ClientRect object, 880 blank-page URL, about:blank, 354 bottom, top, right, and left properties, 392 BlobBuilder object, 694, 863 box model (CSS), 424 Blobs, 691–699, 863 border box model and box-sizing property, building, 694 425 downloading, 694 jQuery.support.boxModel property, 574 files as, 693 box-sizing property, 425 obtaining, methods for, 691 break keyword, 96 reading, 698 break statements, 103 URLs, 695–697 line break interpreted as semicolon, 26 displaying dropped image files, 695 browser property, 571 using, 692 browser sniffing, 330, 346 block scope, 54 using navigator.userAgent, 347 lack of, addressing by using let keyword, browsing contexts, 353 269 browsing history, 345 blocking script execution, 319 history management mechanism in blur effects HTML5, 455, 671–676 motion blur with ImageData, 661 History object, 936 shadowBlur property in canvas, 653 transition, PopStateEvent, 982 blur events, 401, 450 btoa( ) method, Window object, 1004 bubbling alternative to, 453 bubbles property, Event object, 915 Index | 1025
bubbling, 321, 447 Arguments object, 173 event handling in jQuery, 541 restriction in secure subsets, 267 keyboard events to document and window, callee property, Arguments object, 720 452 caller property, Function object, 779 live events, 550 cancelable property, Event object, 915 manually triggered events, 547 cancelBubble property, Event object, 915 mouse events, 453 cancelBubble( ) method, Event object, 548 non-bubbling version of mouse events in IE, cancellation, events, 464 452 application cache updates, 606 place in event propagation after invoking textinput and keypress events, 482 event handlers, 463 canPlayType( ), MediaElement object, 969 buffer property, ArrayBuffer object, 861 Canvas API, 630–665 buffered property, MediaElement, 619, 966 array of bytes in CanvasPixelArray, 688 bufferedAmount property, WebSocket, 1000 canvas dimensions and coordinates, 637 buffers in Node interpreter, 298 Canvas object, 865 bugs in browsers, 325 getContext( ) method, 630, 865 testing for, 330 toDataURL( ) method, 656, 865 button property, Event object, 451, 467, 915 clipping, 652 buttons colors, transparency, gradients, and <button> elements, 397 patterns, 645–648 onclick event handler, 316 compositing, 657 registering event handlers for click event, coordinate system transformations, 638 459 drawing and filling curves, 643–645 Button object, 864 drawing lines and filling polygons, 632 push buttons in forms, 401 drawing red square and blue circle, 631 toggle buttons in forms, 402 drawing sparklines (example), 663–665 buttons property, Event object, 919 drawing text, 650 byte ordering, endianness, 690 graphics attributes defined on context byteLength property, ArrayBuffer object, 861 object, 635–637 byteLength, ArrayBuffer object, 861 hit detection, determining if point is in a byteOffset, ArrayBuffer object, 861 path, 662–663 images, 655–657 C line drawing attributes, 648 caching, 601 path, 631 pixel manipulation, 661–662, 870 (see also application cache) rectangles, 645 memoization of functions, 196 reference, 865–880 Caja secure subset, 268 shadows, 653 calculated values for box dimensions (CSS), <canvas> elements, 630 426 context object, 636 call( ) and apply( ), Function object, 170, 187 canvas property, 871 restrictions in secure subsets, 267 CanvasGradient object, 645, 866 call( ) method, Function object, 136, 779 addColorStop( ) method, 866 callable objects, 191 creating, 874 callbacks, 320 fill or stroke with color gradient, 647 functions passed to setTimeout( ) and CanvasPattern object, 645, 867 setInterval( ), 322 creating, 875 jQuery.ajax( ) function, 567 till or stroke using, 647 passing to jQuery effects methods, 552 CanvasRenderingContext2D callee and caller properties 1026 | Index
save( ) and restore( ) methods, 636 case clauses in switch statements, ending with CanvasRenderingContext2D object, 630, 867– break statement, 96 880 case keyword, 95 arc( ) method, 873 case sensitivity in JavaScript, 21 arcTo( ) method, 873 property names, 376 beginPath( ) method, 873 case-insensitive sorting, arrays of strings, 150 bezierCurveTo( ) method, 874 catch clauses (try/catch/finally), 106 clearRect( ) method, 874 multiple catch clauses, 283 clip( ) method, 652, 874 catching exceptions, 106 closePath( ) method, 874 cd( ) method, ConsoleCommandLine, 884 compositing, 657–660 CDATASection nodes, 381 createImageData( ) method, 661, 874 ceil( ) function, Math object, 793 createLinearGradient( ) method, 647, 874 cellIndex property, TableCell object, 991 createPattern( ) method, 647, 875 cells property, TableRow object, 992 createRadialGradient( ) method, 647, 875 chaining methods, 169 drawImage( ) method, 655, 875 chaining, constructor and method, from drawing and filling curves, 643–645 subclass to superclass, 231–233 drawing rectangles, 645 change( ) method, jQuery, 541 fill( ) method, 875 changedTouches property, touch events, 456 fillRect( ) method, 876 char property, Event object, 454, 919 fillText( ) method, 650, 876 character classes in regular expressions, 253 getImageData( ) method, 661, 876 character sets, 21 graphics attributes, 635–637 CharacterData object, 381 graphics attributes for shadows, 653 characterSet property, Document, 892 isPointInPath( ) method, 662, 877 charAt( ) method, String object, 838 lineTo( ) method, 877 charCode property, Event object, 915 measureText( ) method, 651, 877 charCodeAt( ) method, String object, 501, 838 moveTo( ) method, 877 charset property putImageData( ) method, 661, 878 Document object, 892 quadraticCurveTo( ) method, 878 Script object, 985 rect( ) method, 878 chat restore( ) method, 878 custom Server-Sent Events chat server, 519 rotate( ) method, 878 server using WebSockets and Node, 715 save( ) and restore( ) methods, 870 simple client using EventSource, 516 save( ) method, 879 WebSocket-based chat client, 714 scale( ) method, 879 <checkbox> elements, 402 setTransform( ) method, 879 checked property stroke( ) method, 879 form elements, 399 strokeRect( ) method, 879 Input object, 942 strokeText( ) method, 650, 879 checkValidity( ), FormControl object, 931 transform( ) method, 880 child properties, Element object, 372 translate( ) method, 880 child windows, 356 capability testing, 329 browsing history and, 345 caption property, Table object, 990 childElementCount, Element object, 373, 903 capturing event handlers, 458, 463, 545 childNodes property, Node object, 371, 976 mouse events in IE, 468 children property, Element object, 372, 375, carriage returns, 22 903 Cascading Style Sheets (see CSS) children( ) method, jQuery, 580 Chrome, 471 Index | 1027
(see also web browsers) object-oriented programming with, 215– current version, 327 228 implementation of Filesystem API, 700 borrowing methods, 224 JavaScript in URLs, 316 comparison methods, 221–224 textInput event, 453 constructor overloading and factory class attribute, 10, 116, 136 methods, 227 Array, 158 enumerated types (example), 217–219 HTML elements, 368, 376 private state, 226 testing for true function object, 191 Set class (example), 215–217 class fields and methods (Java classes), 205 standard conversion methods, 219 class members, in strongly-typed object- partial class hierarchy of document nodes, oriented languages, 205 363 classes, 30, 199–246 prototypes and, 200 (see also modules; objects) scripting CSS classes, 437–440 augmenting by adding methods to subclasses, 228 prototype, 208 class hierarchies and abstract classes, built-in, automatically predefined in all 234–238 windows, 359 composition versus subclassing, 233 constructors, 201 constructor and method chaining, 231– and class identity, 203 233 constructor property, 203 defining, 229 defining for CSS properties, 417 classList property, 438, 533 defining, example, 8 approximating functionality, example of, defining, multiple windows and, 359 438–440 determining class of an object, 210–215 Element object, 903 duck-typing, 213 className property, 308, 368, 376, 438–440 using constructor name as class Element object, 308, 903 identifier, 211 clear( ) method using constructor property, 211 ConsoleCommandLine object, 884 using instanceof operator, 210 Storage object, 988 in ECMAScript 5, 238 clearData( ), DataTransfer object, 889 defining immutable classes, 239–241 clearInterval( ) function, 297 encapsulating object state, 241 clearInterval( ) method, 342 making properties nonenumerable, 238 Window object, 1004 preventing class extensions, 242 WorkerGlobalScope object, 1010 property descriptors, 244–246 clearQueue( ) method, jQuery, 558 subclasses, 243 clearRect( ), CanvasRenderingContext2D, 645, getting and setting CSS classes, 532 874 getting class of an object, 136 clearTimeout( ) function, 297 instanceof operator, 75 clearTimeout( ) method Java Window object, 1005 instantiating, 291 WorkerGlobalScope object, 1010 querying and setting static fields in clearWatch( ), Geolocation object, 933 Rhino, 291 click events, 467 Java-style, in JavaScript, 205–208 detail property, 451 defining complex class, 206 registering event handlers for, 11 features not supported in JavaScript, registering event handlers on button 208 element for, 459 function defining simple classes, 205 click( ) method, 540 1028 | Index
Element object, 906 closed property, Window objects, 356 client properties, document elements, 395 CloseEvent object, 881 client sniffing, 330 closePath( ), CanvasRenderingContext2D, client-side JavaScript, 8–12, 307 633, 874 building web applications with, 338 closest( ) method, jQuery, 581 compatibility and interoperability issues, closing windows, 356 325 Closure library, 339 keeping HTML content separate from closures, 180–185 JavaScript behavior, 458 access to outer function arguments, 185 loan calculator (example), 12–18 combining with property getters and setters, scripting HTML document content, 9 183 security, 333 lexical scoping rule for nested functions, threading model, 322 181 client-side storage, 587–612 private property accessor methods using, application storage and offline web 184 applications, 601–607 property accessor methods using, 226 application cache manifest, 601–603 shorthand functions (expression closures), cache updates, 603–607 282 cookies, 593–599 using in uniqueInteger( ) function storage with cookies, 597–599 (example), 182 IE userData persistence, 599–601 code property localStorage and sessionStorage properties, DOMException object, 900 589 FileError object, 924 security, privacy, and, 589 GeolocationError object, 934 client-side storage and offline web applications MediaError object, 970 offline web applications, 608–612 codepoints (Unicode), 36, 481 clientHeight and clientWidth properties, color stops, 647 Element object, 392, 904 colorDepth or pixelDepth property, Screen clientLeft and clientTop properties, Element object, 984 object, 904 colors ClientRect object, 880 background-color property, 421 clientX and clientY properties, Event object, gradients in canvas, 646 451, 467, 916 shadowColor property, 653 clip property, 428 specifying for paths in canvas, 868 clip( ), CanvasRenderingContext2D, 648, 652, specifying in canvas, 645 874 specifying with CSS, 426 clone( ) method, jQuery, 539 colSpan property, TableCell object, 991 cloneNode( ) method, Node object, 382, 978 Comet, 491 clones, structured, 672 Server-Sent Events with, 515–521 close( ) method transport mechanisms for, 493 distinguishing between Window and comma operator (,), 85 Document objects, 356 commands Document object, 894 ConsoleCommandLine objects, 883 EventSource object, 921 text editing, 410 generators, 278 comments, 4 MessagePort object, 972 Comment node, 881 WebSocket object, 714, 1000 conditional, 331 Window object, 1005 createComment( ), Document object, 382 WorkerGlobalScope object, 682, 1010 creating Comment node, 894 Index | 1029
CSS handling of, 414 methods, 882 JavaScript code in URLs, 315 console tools, 3 styles of, 23 console.log( ) function, 686 compareDocumentPosition( ), Node object, ConsoleCommandLine object, 883 978 const keyword, 269 comparison methods, implementation in constants classes, 221–224 block scope and use of let keyword, 269 compareTo( ) method, 222 fields declared final in Java classes, 208 equals( ) method, 221 constructor chaining, 228 comparison operators, 62, 73, 223 from subclass to superclass, 231–233 comparisons constructor objects, 205 objects, 45 constructor property, 135 primitive values, 44 identifying class of an object, 211 compatibility and interoperability, 325–332 restrictions in secure subsets, 267 browser testing, 330 constructors, 163, 782 compatibility libraries, 328 class, 201 conditional comments in Internet Explorer, and class identity, 203 331 constructor property, 203 feature testing, 329 client-side, in WorkerGlobalScope objects, graded browser support, 329 684 quirks mode and standards mode, 330 constructor property of an object, 811 compatMode, Document object, 330, 892 defined, 30 complete property, Image object, 555, 941 interactive windows and, 359 compositing in canvas, 657–660, 869 invoking, 170 locally rather than globally, 659 object prototypes and, 118 composition overloading, 227 subclassing versus, 233 prototype property, 135 using with partial application of functions, for typed arrays, 997 196 using name of as class identifier, 211 computed styles, 416, 532 contains( ) function, 571 querying, 436–437, 436 contains( ) method, DOMTokenList, 438, 902 concat( ) method content Array object, 150, 724 generating document content at load time, String object, 839 318 concatenating strings, 38 simple client-side script for revealing, 309 conditional comments in Internet Explorer, content-box model, 425 331 Content-Type headers conditional operator (?:), 82 automatically set for request by conditional statements, 87, 92 XMLHttpRequest, 505 in array comprehensions, 281 HTTP requests, 496 else if, 94 overriding incorrect MIME type in response, if, 92 501 switch, 95 contentDocument, IFrame object, 939 configurable attribute (properties), 116, 131 contentEditable property, Element object, 409 deletion of properties, 124 contents( ) method, jQuery, 581 extensible attribute used with, 137 contentType option, 562 confirm( ) method, Window object, 348, 1005 contentWindow, IFrame object, 357, 939 console API, 3 context menus, 467 Console object, 882 context property, 947 1030 | Index
jQuery objects, 529 createDocumentType( ), DOMImplementation contextmenu events, 452, 467 object, 901 continue statements, 104 createElement( ), Document object, 382, 895 semicolon interpreted as line break, 26 createElementNS( ), Document object, 382, contractions and possessives in English 627, 895 language strings, 37 createEvent( ), Document object, 895 control property, Label object, 962 createHTMLDocument( ), control structures, 6, 87 DOMImplementation object, 901 (see also statements) createImageData( ), controls attribute, <audio> and <video> CanvasRenderingContext2D, 661, elements, 616 874 controls property, MediaElement object, 966 createIndex( ) method, object store, 707 cookie property, Document object, 405, 892 createLinearGradient( ), cookies, 588, 593–599 CanvasRenderingContext2D, 647, attributes, lifetime and scope, 594 874 determining if they are enabled, 594 createObjectStore( ) method, IndexedDB limitations on size and number of, 597 objects, 707 reading, 596 createObjectURL( ) function, 695 storage with, 597–599 createObjectURL( ), URL object, 998 storing, 595 createPattern( ), CanvasRenderingContext2D, cookiesEnabled( ), Navigator object, 348 647, 875 coordinate system transformations, 638–643, createProcessingInstruction( ), Document 869 object, 895 Coordinated Universal Time (UTC), 742 createRadialGradient( ), coordinates CanvasRenderingContext2D, 647, canvas, 637 875 images, 655 createRange( ) method, 408 converting document to viewport createStyleSheet( ), Document object, 442 coordinates, 396 createTBody( ) method, Table object, 990 document and viewport, 390 createTextNode( ), Document, 382, 895 document, as scrollbar offsets, 394 createTFoot( ) method, Table object, 990 Geocoordinates object, 933 createTHead( ) method, Table object, 990 position of mouse in window coordinates, Crockford, Douglas, 119, 266, 268 451 cross-document messaging, 336, 676–680, coords property, Geoposition object, 935 677 CORS (“Cross-Origin Resource Sharing”) Cross-Document Messaging API, 455 headers, 511 “Cross-Origin Resource Sharing”, 335 cos( ) function, Math object, 794 cross-origin HTTP requests, 496, 511–513 count( ) method, Console object, 882 requesting link details with HEAD and create( ) function, 118, 811 CORS, 512 adding properties to newly created object, cross-site scripting (XSS), 336 133 CSS (Cascading Style Sheets), 413–443 createCaption( ) method, Table object, 990 box model and positioning details, 424 createComment( ), Document object, 894 classes, selecting elements by, 368 createDocument( ), DOMImplementation, color specifications, 646 901 color, transparency, and translucency, 426 createDocumentFragment( ), Document element display and visibility, 426 object, 385, 894 getting and setting CSS attributes, 532 getting and setting CSS classes, 532 Index | 1031
important style properties, 419 custom events, using jQuery with, 549 overlapping translucent windows customError, FormValidity object, 932 (example), 429–431 overview, 414 D partial visibility, overflow and clip, 428 positioning elements, 420–423, 472–475 data properties, 129 querying computed styles, 436–437 attributes of, 131 revolutionary new features of, 418 data property scripting CSS classes, 437–440 CharacterData object, 381 scripting inline styles, 431–435 Comment object, 881 animations, 433–435 Event object, 453, 481, 544, 919 scripting stylesheets, 440–443 ImageData object, 688, 942 selectors, 369 MessageEvent object, 677, 971 styles, specified for Element object, 308 ProcessingInstruction object, 982 use with JavaScript to style presentations of Text node, 993 HTML, 10 data storage APIs for web applications, 311 web page styled with CSS (example), 417 data types, 4, 29–56 css( ) method, jQuery, 532 booleans, 40 CSSOM-View Module, 390 classes and, 210 CSSRule object, 441, 885 determining class of an object with cssRules property, CSSStyleSheet, 441, 887 constructor property, 211 CSSStyleDeclaration object, 886 determining class of an object with computed styles, 436 instanceof, 210 describing styles associated with selector, duck-typing, 213 441 standard conversion methods, 219 properties corresponding to shortcut using constructor name as class properties, 432 identifier, 211 using in scripting inline styles, 431 conversions, 31, 45–52 CSSStyleSheet object, 440, 887 equality and, 47 creating, 442 explicit, 47–49 disabled property, 440 object to primitive, 49–52 inserting and deleting rules, 441 summary listing of, 45 querying, inserting, and deleting stylesheet function argument, 174 rules, 441 Java, conversions in Rhino, 293 cssText property jQuery's Ajax data types, 563 CSSRule object, 885 methods, 30 CSSStyleDeclaration object, 433, 441, 886 mutable and immutable types, 31 ctrlKey property, 451, 467, 485 numbers, 31–36 Event object, 916 binary floating-point and rounding currentSrc, MediaElement object, 966 errors, 34 currentStyle property dates and times, 35 Element object, 904 floating-point literals, 32 in Internet Explorer (IE), 437 integer literals, 32 currentTarget property, Event object, 543, 916 objects and arrays, 5 currentTime, MediaElement object, 618, 967 operand and result type, 64 currying, 188 primitive and object types, 29 cursor, opening in IndexedDB, 706 text, 36–40 curves, drawing and filling in canvas, 643–645, escape sequences in string literals, 37 874 pattern matching, 39 string literals, 36 1032 | Index
working with strings, 38 seMilliseconds( ) method, 754 typeof operator, 82 setDate( ) method, 753 variable declaration and, 52 setFullYear( ) method, 753 data( ) method, jQuery, 536, 584 setHours( ) method, 754 data:// URLs, 926, 927 setMinutes( ) method, 755 databases setMonth( ) method, 755 client-side, 705–713 setSeconds( ) method, 756 client-side database functionality in setTime( ) method, 756 browsers, 588 setUTCDate( ) method, 757 dataset attributes, 377 setUTCFullYear( ) method, 757 using to create image rollovers, 615 setUTCHours( ) method, 758 dataset property, Element object, 377, 904 setUTCMilliseconds( ) method, 758 DataTransfer object, 454, 475–481, 888 setUTCMinutes( ) method, 759 files property, 505, 694 setUTCMonth( ) method, 759 dataTransfer property, Event object, 454, 475, setUTCSeconds( ) method, 760 916 setYear( ) (deprecated), 760 DataView object, 890 static methods, 745 methods reading/writing values from toDateString( ) method, 760 ArrayBuffer, 690 toGMTString( ) method, 761 Date( ) constructor, 742 toISOString( ) method, 761 datepicker( ) method, 586 toJSON( ) method, 762 dates and time toLocaleDateString( ) method, 762 Date class, 30 toLocaleString( ) method, 763 toString( ) method, 50 toLocaleStringTime( ) method, 763 Date object, 742–766 toString( ) method, 763 conversions to strings and numbers, 51 toTimeString( ) method, 764 getDate( ) method, 746 toUTCString( ) method, 764 getDay( ) method, 747 UTC( ) method, 765 getFullYear( ) method, 747 valueOf( ) method, 50, 766 getHours( ) method, 747 quick tutorial on, 35 getMilliseconds( ) method, 747 serializing Date objects to ISO-formatted getMinutes( ) method, 748 date strings, 138 getMonth( ) method, 748 dblclick event, 452, 467 getSeconds( ) method, 748 dblclick( ) method, jQuery, 541 getTime( ) method, 748 debug( ) method, Console object, 882 getTimezoneOffset( ) method, 749 debugger statements, 110 getUTCDate( ) method, 749 debugging Worker threads, 686 getUTCDay( ) method, 750 decimal fractions, binary floating-point getUTCFullYear( ) method, 750 representation, 35 getUTCHours( ) method, 750 declaration statements, 87, 89 getUTCMilliseconds( ) method, 750 var statement, 90 getUTCMinutes( ) method, 751 decodeURI( ) function, 766 getUTCMonth( ) method, 751 decodeURIComponent( ) function, 343, 595, getUTCSeconds( ) method, 751 767 getYear( ) method, 751 dedicated workers, 684 methods, 743 default actions of events, 447 now( ) method, 752 defaultCharset, Document object, 892 parse( ) method, 752 defaultChecked property prototype property, 118 Checkbox object, 402 Index | 1033
Input object, 943 deltaX, deltaY, and deltaZ properties, Event defaultPlaybackRate, MediaElement object, object, 453, 471, 920 618, 967 denial-of-service attacks, 338 defaultPrevented, Event object, 464, 916 dequeue( ) method, jQuery, 558 defaultSelected, Option object, 980 descendant operator (. .), 285 defaultValue property designMode, Document object, 409, 893 Input object, 943 destructuring assignment, 272 Output object, 981 using with Iterator ( ) function in for/in loop, TextArea object, 994 277 defaultView property, Document object, 892 detach( ) method, jQuery, 540 defer property, Script object, 985 detachEvent( ) method, 459, 923 deferred execution of scripts, 319 detail property, Event object, 451, 471, 916 __defineGetter__( ) and __defineSetter__( ) device-dependent and -independent events, methods, 134, 375 448 defineProperties( ) function, 812 DHTML (Dynamic HTML), 310 creating or modifying multiple properties, dialog boxes, 348–351 132 HTML dialog box displayed with defineProperty( ) function, 101, 134, 813 showModalDialog( ), 349 creating new property or setting attributes, repeated, in cross-site scripting attacks, 132 337 defining configurable, read-only properties, repeated, in denial-of-service attacks, 338 124 dialogArguments, Window object, 349, 1002 making length property of array read-only, die( ) method, jQuery, 550 145 dimensions, canvas, 637 making properties nonenumerable, 238 dir property, Document object, 893 delay( ) method, jQuery, 557 dir( ) method delegate( ) method, jQuery, 549 Console object, 882 delete operator, 62, 84 ConsoleCommandLine object, 884 deleting array elements, 146 directives, 110 deleting configurable properties of global DirectoryEntry objects, 701 object, 125 dirxml( ) method deleting properties, 124 Console object, 882 removing XML attributes and tags in E4X, ConsoleCommandLine object, 884 286 disabled property side effects, 88 CSSStyleSheet object, 887 deleteCaption( ) method, Table object, 991 FieldSet object, 923 deleteCell( ) method, TableRow object, 992 FormControl object, 930 deleteData( ) method Link object, 963 Comment node, 881 Option object, 980 Text node, 993 Style object, 989 deleteRow( ) method disabling animations in jQuery, 551 Table object, 991 dispatchEvent( ), EventTarget object, 922 TableSection object, 992 dispatchFormChange( ), Form object, 929 deleteRule( ), CSSStyleSheet object, 441, 888 dispatchFormInput( ), Form object, 929 deleteTFoot( ) method, Table object, 991 display property, 426 deleteTHead( ) method, Table object, 991 division by zero, 34 deletion methods in jQuery, 953 DnD (see drag and drop) deltaMode property, Event object, 920 do/while loops, 98 doctype declarations 1034 | Index
quirks mode and standards mode, 330 using to reverse order of children of a Node, strictness of, 369 386 doctype property, Document object, 893 documents, 361–411 Document object, 308, 361, 891–898 altering structure using jQuery, 537–540 addEventListener( ) method, 459 associating CSS stylesheet with, 415 close( ) method, 356 attributes of elements, 375–378 compatMode property, 330 creating, inserting, and deleting nodes, 382– cookie property, 593 387 parsing, 596 creating nodes, 382 createDocumentFragment( ) method, 385 inserting nodes, 383 createElement( ) method, 382 removing and replacing nodes, 384 createElementNS( ) method, 382 using DocumentFragments, 385 createStyleSheet( ) method, 442 Document properties, 405 createTextNode( ) method, 382 editable content, 408–411 designMode property, 409 document and element geometry and elementFromPoint( ) method, 393 scrolling, 390–396 events, 898 element content, 378–382 forms property, 398 elements as Window object properties, 351 getElementById( ) method, 352, 364 generating content at load time, 318 getElementsByClassName( ) method, 368 generating table of contents (example), 387– getElementsByTagName( ) method, 159, 390 366 HTML forms, 397–404 location property, 343 JavaScript in web documents, 310 methods, 894–898 load events, 465–467 open( ) method, 346 loading new, 344 parsed HTTP responses available as, 500 nested HTML documents, 353 properties, 405, 892 origin of, 334, 590 queryCommandEnabled( ) method, 410 overview of DOM, 362 querySelector( ) method, 370 querying selected text, 407 querySelectorAll( ) method, 370, 440 selecting elements in, 364–371 readyState property, 323, 465 structure and traversal, 371–375 removeEventListener( ) method, 459 documents as trees of elements, 372– same-origin policy applied to properties, 375 335 documents as trees of nodes, 371 styleSheets property, 440, 441 write( ) method, 406 URL property, 343 DocumentType object, 899 write( ) method, 318, 324, 346, 406 Dojo, 338 writeln( ) method, 407 dojox.secure, 268 document property, Window object, 308, Sizzle library, 370 1002 DOM (Document Object Model) document.all[ ] collection, 371 DOM Level 2 Events specification, 325 documentElement, Document object, 367, DOM Level 3 Events specification, 448, 452, 391, 893 453 DocumentFragment object, 364, 385, 898 key property, 485 creating, 894 proposed method, 920 implementing insertAdjacentHTML( ) proposed properties, 919 using innerHTML, 386 event cancellation in current Events module querySelector( ) and querySelectorAll( ) draft, 464 methods, 370 implementation of types as classes, 374 Index | 1035
overview, 362 introduction to, 283–287 textinput event, 481 each( ) function, 572 XML objects and E4X standard, 284 each( ) method, jQuery, 529 domain property, Document object, 405, 893 easing functions, 556 domains adding to jQuery, 584 domain attribute, cookies, 594 ECMAScript, 2 setting, 596 JavaScript extensions, 265 problems with same-origin policy and ECMAScript 5 subdomains, 335 array methods, 153–157, 159, 529 DOMContentLoaded event, 324, 450, 465 classes in, 238 DOMException object, 899 defining immutable classes, 239–241 DOMImplementation object, 900 defining nonenumerable properties, 238 DOMMouseScroll objects, 471 encapsulating object state, 241 DOMSettableTokenList object, 901 preventing class extensions, 242 DOMTokenList object, 438, 902 property descriptors, 244–246 drag and drop, 475–481 subclasses, 243 access to files user drops over element, 505 RegExp literals and object creation, 252 custom drag source, 476 reserved words, 24 DataTransfer objects, 888 ECMAScript for XML (see E4X) displaying dropped image files with Blob editable content in documents, 408–411 URLs, 695 editor components in frameworks, 410 drag source events, 476 effectAllowed, DataTransfer object, 476, 477, drag( ) function evoked from mousedown 888 event handler, 468 Element class, 364 dragging document elements, 468–471 element expressions in array initializers, 58 drop targets, 477 Element object, 308, 902–909 dropping local files into browser for script attributes property, 378 access, 694 contentEditable property, 409 HTML5 drag-and-drop API, 454 dataset property, 377 list as drop target and drag source defining custom methods, 374 (example), 478–481 event handlers, 909 obtaining files from DnD API and uploading getAttribute( ) and setAttribute( ) methods, via HTTP request, 508 376, 433 draggable attribute, 476 getBoundingClientRect( ) method, 396 drawImage( ), CanvasRenderingContext2D, hasAttribute( ) method, 377 655, 875 implementing outerHTML property, using drawing context objects, 630 innerHTML, 384 dropEffect, DataTransfer object, 476, 888 innerHTML property, 379 dropzone attribute, 477 methods, 906–909 duck-typing, 213 Node objects, 371 duration property, MediaElement object, 618, offsetLeft and offsetTop properties, 394 967 offsetParent property, 395 duration, animated effects, 551, 956 outerHTML property, 379 passing to jQuery effects methods, 552 properties, 903 Dynamic HTML (DHTML), 310 properties, element-based document traversal API, 372 E removeAttribute( ) method, 377 E constant (Math), 794 representing <style> and <link> elements, scripting stylesheets, 440 E4X (ECMAScript for XML), 274 1036 | Index
style property, 431 Document object, 893 elementFromPoint( ), Document, 393, 895 HTMLDocument object, 367 elements empty statements, 89 array, 141 empty strings, 36 attributes of, 375–378 empty( ) method, jQuery, 540 attributes as Attr nodes, 378 enableHighAccuracy option, Geolocation dataset attributes, 377 methods, 934 non-HTML, getting and setting, 376 encapsulation computed style, 416 object state, in ECMAScript 5, 241 content, 378 state variables, 226 content as HTML, 379 encodeURI( ) function, 767 content as plain text, 380 encodeURIComponent( ) function, 595, 768 content as Text nodes, 381 encoding HTTP request body, 502–507 copying with jQuery, 539 encoding property, Form object, 399 deleting using jQuery, 540 enctype property, Form object, 928 display and visibility properties (CSS), 426 end( ) method document, as Window properties, 351 jQuery, 582 documents as trees of, 372–375 TimeRanges object, 996 geometry and scrolling, 390–396 ended property, MediaElement object, 967 getting and setting content, 534 endianness, 690 getting and setting element data, 536 enumerable attribute (properties), 116, 131 getting and setting geometry, 534 propertyIsEnumerable( ) test, 125 HTML elements and attributes, 910–913 enumerable properties, 101 HTML form, 397 arrays, enumeration by for/each loop, 274 inserting and replacing in documents with Object.propertyIsEnumerable( ) method, jQuery, 537 822 jQuery element methods, 950 returning own enumerable property names, media, 965–970 821 positioning with CSS, 420 enumerated types, 217–219 querying geometry of, 392 classes representing cards, 218 the selected elements in jQuery, 528 comparisons, 223 selecting document elements, 364 enumerating properties, 126–128 selecting HTML form elements, 398 order of, in for/in loops, 101 size, positioning, and overflow, 394 eq( ) method, jQuery, 578 wrapping around other elements, using equality comparisons jQuery, 539 binary floating-point and rounding errors, elements property 35 FieldSet object, 923 type conversions and, 47 Form object, 399, 928 equality operators (see = (equals sign), under else clauses in nested if statements, 93 Symbols) else if statements, 94 equals( ) method, defining for classes, 221 <embed> elements, 537 error property embedding JavaScript in HTML, 311–317 FileReader object, 925 event handlers in HTML, 315 MediaElement object, 620, 967 JavaScript in URLs, 315 Error( ) constructor, 769 <script> element, 312 error( ) method script type, 314 Console object, 882 scripts in external files, 313 jQuery, 541 embeds property ErrorEvent object, 913 Index | 1037
errors event handler context, 461 Error class, 30, 106 event handler scope, 461 error handlers, similarity to events, 449 event propagation, 463 Error object, 769–771 handler return value, 462 javaException property, 293 order of invocation, 462 message property, 771 jQuery, 542 name property, 771 mousewheel events, 472–475 toString( ) method, 771 onerror property, Window object, 351 handling in Window objects, 351 properties defined by HTMLElements, 375 property access, 123 properties of Window, Document, and ES5 (see ECMAScript 5) Element objects, 309, 1007 escape sequences registering (see registering event handlers) in string literals, 37 text input elements, 403 Unicode, 22 WebSocket, 1000 escape( ) function, 771 Worker object, 1009 eval( ) function, 79–81, 772 WorkerGlobalScope, 1011 removal in secure subsets, 267 XMLHttpRequest object, 1017 EvalError object, 774 readystatechange events, 499 evaluation expressions, 79–81 XMLHttpRequestUpload, 1018 eval( ) function, 80 event listeners, 320 global eval( ), 80 (see also event handlers) strict eval( ), 81 same-origin policy, 334 evaluation order, operators, 66 Event object, 542, 914–920 evaluation, modules, 302 constants defining values of eventPhase event capturing, 447, 458, 463 property, 914 Internet Explorer, setCapture( ) for mouse defaultPrevented property, 464 events, 468 jQuery, 542 jQuery event handlers and, 545 methods, 918 event handlers preventDefault( ) method, 464 advanced event handler registration with properties, 915 jQuery, 544 proposed method, DOM Level 3 ApplicationCache object, 860 specification, 920 defined, 10 proposed properties, DOM Level 3 defining for FileReader, 698, 926 specification, 919 defining for offline web application, 609 returnValue property, 464 defining, onclick handler (example), 10 stopImmediatePropagation( ) method, 465 deregistering with jQuery, 546 stopPropagation( ) method, 464 Element objects, 909 event propagation, 463 EventSource object, 921 cancelling, 464 form and form element, 400 defined, 447 form controls, 931 stopping, 919 Form objects, 929 event property, Window object, 460, 1002 functions for, 320 event type, 445 in HTML, 315 event-driven JavaScript, 320 HTTP progress events, 507 event-driven phase of execution, 318 HTTP upload progress event, 508 eventPhase property, Event object, 916 invoking, 460–465 constants defining values of, 914 event cancellation, 464 events, 445–489 event handler argument, 460 Ajax in jQuery, 570 1038 | Index
categories of, 448 supported by Document objects, 898 createEvent( ), Document object, 895 testing if mouse event is over current path in default actions associated with, 447 canvas, 662 defined, 445 testing if mouse event is over painted pixel device-independent, 332 in canvas, 663 document load, 465–467 text, 481–484 DOM (Document Object Model), 453 touchscreen and mobile, 456 drag and drop, 475–481 types of, 448 ErrorEvent object, 913 WebSocket, 713 event emitters in Node, 297 EventSource object, 515–521, 921 event objects, 446 constants defining values of readyState event propagation, 447 property, 921 event target, 446 emulating with XMLHttpRequest, 517– event type or event name, 445 519 handling application cache events, 604– using in simple chat client, 516 607 EventTarget object, 922 handling with jQuery, 540–550 every( ) method, Array object, 154, 725 advanced event handler registration, excanvas.js library, 328 544 exceptions custom events, 549 handling with try/catch/finally statements, deregistering event handlers, 546 106 event handler registrations methods, multiple catch clauses, 283 540 Java, handling as JavaScript exception in Event object, 542 Rhino, 293 live events, 549 throwing, 106 triggering events, 547 thrown by Worker objects, 681 hashchange event, 672 exec( ) method, RegExp objects, 262, 585, 831 HashChangeEvent object, 935 execCommand( ), Document object, 410, 895 HTML5, 454 execution context, 353 HTTP abort events, 510 event handlers, 461 HTTP progress events, 507–510 execution model, Worker threads, 683 HTTP timeout events, 510 execution of JavaScript programs, 317–324 implementing Java event listeners with client-side threading model, 322 JavaScript in Rhino, 292 client-side timeline, 323 invocation of event handlers, 460–465 event-driven, 320 jQuery, 955 synchronous, asynchronous, and deferred keyboard, 484–489 scripts, 318 legacy event types, 449 exp( ) function, Math object, 794 media, 620, 968 expires property, data saved with userData, message, 677, 681, 971, 972 600 mouse, 467–471 explicit conversions of types, 47–49 mousewheel, 471–475 ExplorerCanvas project, 630 overview, 320 exponential notation, 32, 48, 804 page transition, 981 expression closures, 282 popstate, 982 expression statements, 87 progress, 983 expressions, 57 registering event handlers, 457–460 arithmetic, 66–70 Server-Sent Events with Comet, 515–521 + (addition or string concatenation) storage, 592, 988 operator, 67 Index | 1039
bitwise operators, 69 F unary arithmetic operators, 68 assignment, 77 Facebook, FBJS secure subset, 269 assignment with operation, 78 factory functions comma operator (,), 85 class factory function and method chaining, conditional operator (?:), 82 231 defined, 5 creating and initializing new object, 200 delete operator, 84 factory methods, 227 evaluation, 79–81 fade effects before for keyword in array fadeIn( ) and fadeOut( ) methods, 551, 552 comprehensions, 281 fadeTo( ), 552 function definition, 59, 164, 165 queued, animate( ) method and, 555 generator, 281 fadeout animation (example), 433–435 invocation, 61, 167 FALLBACK section, application cache logical, 75 manifest, 603 logical AND (&&) operator, 75 false and true values, 45 logical NOT (!) operator, 77 FBJS secure subset, 269 logical OR (||) operator, 76 feature testing for browsers, 329 object and array initializers, 58 Fibonacci numbers, generator function for, object creation, 61 278 operator overview, 62–66 FieldSet object, 923 primary, 57 File API specification, 455 property access, 60, 168 FileEntry objects, 701 relational, 71 FileError object, 924 comparison operators, 73 FileList object, 693 equality and inequality operators, 71 filename property, ErrorEvent object, 913 in operator, 74 FileReader object, 924–927 instanceof operator, 75 constants defining values of readyState statements versus, 6 property, 925 typeof operator, 82 event handlers, 926 void operator, 85 events tracking progress of asynchronous I/ extend( ) function, 127, 572 O, 455 extensibility of objects, 818 events triggered on, 455 extensible attribute, 116, 137 methods, 925 extensions, 269–287 properties, 925 constants and scoped variables, 269 reading Blobs, 698 destructuring assignment, 272 FileReaderSync object, 699, 927 E4X (ECMAScript for XML), 283–287 files iteration, 274–282 as Blobs, 693 array comprehensions, 280 File object, 923 for/each loop, 274 local files and XMLHttpRequest, 495 generator expressions, 281 monitoring HTTP upload progress, 508 generators, 277–280 Node file and filesystem API, 299 iterators, 274–277 uploading with HTTP POST request, 505 preventing, 810, 821 files property preventing class extensions in ECMAScript DataTransfer object, 478, 694, 889 5, 242 Input object, 943 shorthand functions (expression closures), filesystems, 700–705 282 client-side storage by web applications, 588 1040 | Index
reading user-selected files with JavaScript, Float64Array class, 996 333 floating-point literals, 32 using asynchronous filesystem API, 701 floating-point values, 31 using synchronous filesystem API, 704 binary floating-point and rounding errors, working with files in local filesystem, 700 34 FileUpload elements, value property, 334 floor( ) function, Math object, 795 FileWriter objects, 701 fn prototype object (jQuery), 583 fill( ), CanvasRenderingContext2D, 633, 875 focus events, 401, 450 fillRect( ), CanvasRenderingContext2D, 645, bubbling focusin and focusout events, 453 876 event handler registration with jQuery, 541 fills keyboard focus for document elements, clipped, 652 452 colors, gradients, and patterns in Canvas, focus( ) method 645–648, 868 Element object, 906 fillStyle property, Window object, 1005 CanvasRenderingContext2D, 635, font property, 416, 869, 871 871 text in canvas, 650 fillText( ), CanvasRenderingContext2D, 650, fontFamily property, 437 876 fonts filter property (IE), 428 font-size and font-weight, and color style filter( ) method properties, 431 Array object, 154, 726 web fonts in CSS, 418 jQuery, 540, 579 for loops, 98 filtering user input, 482–484 calling jQuery.each( ) instead, 529 finally clauses (try/catch/finally), 106 continue statements in, 104 find( ) method, jQuery, 580 iterating arrays, 146 finite numbers, 784 let keyword used as loop initializer, 270 Firebug extension (Firefox), 3 variables declared with let keyword, 270 Firefox, 347 for/each loops, 274 (see also web browsers) in array comprehensions, 281 changes to History API in Firefox 4, 673 defined in E4X, iteration through lists of charCode property, 481 XML tags and attributes, 286 current version, 327 for/in loops, 100 DOMMouseScroll events, 471 in array comprehensions, 281 ECMAScript 5 array methods, 160 continue statements in, 104 global compositing approach, 659 enumerating properties, 126–128 JavaScript versions and extensions, 265, extension to work with iterable objects, 270 274–277 first( ) and last( ) methods, jQuery, 578 iterating arrays, 147 :first-line and :first-letter pseudo-elements iterating through methods, fields and (CSS), 370 properties of Java classes and firstChild and lastChild properties, Node objects, 292 object, 371, 976 let keyword in, 270 firstElementChild, Element object, 373, 904 property enumeration order, 101 fixed positioning of elements, 420 using with associative arrays, 121 fixed-point notation for numbers, 805 forEach( ) method, Array object, 148, 153, flags in regular expressions, 259 726 Flash plug-ins, scripting, 336 <form> elements Float32Array class, 996 Index | 1041
action, encoding, method, and target Input object, 943 attributes, 399 FormValidity object, 932 method attribute, 399 forward( ) method, History object, 345, 936 setting form-submission attributes of, 375 fractions, binary floating-point representations triggering submit event on, 548 of, 35 Form object, 927–929 fragment identifiers in URLs, 672 elements property, 399 <frame> and <frameset> elements event handlers, 929 (deprecated), 353 methods, 929 frameElement property, Window object, 357, properties, 928 1002 referred to as this.form by form element frames event handlers, 401 inability to close, 356 submit( ) and reset( ) methods, 400 multiple windows and frames, 353–360 form property, 400, 401 relationships between frames, 356 FormControl object, 930 viewport, 390 Label object, 962 frames property, Window object, 357, 1002 Meter object, 973 frameworks, client-side, 328, 338 Option object, 980 freeze( ) function, 137, 814 Progress object, 983 fromCharCode( ) method, String object, 839 form-encoded HTTP requests, 502–507 fromElement property, Event object, 916 encoding an object, 502 frozen objects, 814, 819 file upload with POST request, 505 fs (file and filesystem) module, Node, 299 JSON-encoded body, 504 function calls, 96 making GET request, 503 (see also functions, invoking) making HTTP POST request, 503 as expression statements, 88 multipartform=data requests, 506 Function class, 30 XML-encoded body, 504 toString( ) method, 50 formAction property function declaration statements, 91, 165 Button object, 864 function definition expressions, 165 Input object, 943 function declaration statements versus, 92 format control characters (Unicode), 22 function keyword, 59, 164 FormControl object, 929 creating a variable, 358 event handlers, 931 Function object, 775–781 methods, 931 apply( ) method, 776 properties, 930 arguments property, 777 FormData object, 506, 931 bind( ) method, 189, 208, 778 formEnctype property call( ) method, 136, 779 Button object, 864 caller property, 779 Input object, 943 defining your own properties, 178 formMethod property length property, 780 Button object, 864 methods, 776 Input object, 943 properties, 775 formNoValidate property prototype property, 780 Button object, 864 toString( ) method, 780 Input object, 943 function scope, 31 forms property, Document object, 367, 398, and hoisting, 54 893 as private namespace in modules, 248–250 formTarget property Function( ) constructor, 190 Button object, 865 removal in secure subsets, 267 1042 | Index
functions, 163–197 as values, 176–178 Ajax utility functions in jQuery, 560 defining your own function properties, arguments and parameters, 171–176 178 argument types, 174 variables declared with var or let, 271 optional parameters, 171 using object properties as arguments, G 174 variable-length argument lists, 172 g (global matching) in regular expressions, arguments[ ] array, 719 259 bind ( ) method, 188 garbage collection, 30 call( ) and apply( ) methods, 187 generator expressions, 281 callable objects, 191 generators, 277–280 closures, 180–185 pipeline of, 279 constructor, 782 restarting with send ( ) or throw ( ) method, defined, 6, 30 280 defining, 164–166 Geocoordinates object, 933 nested functions, 166 Geolocation API, 668–671 definition expressions, 59 example demonstrating all features, 670 demonstrating control structure statements, using to display a map, 669 7 Geolocation object, 933 Function( ) constructor, 190 geolocation property, Navigator object, 348, generator, 277–280 668, 974 global, 25, 781 GeolocationError object, 934 higher-order, 193 geometrical, coordinate-based view of invocation expressions, 61 documents, 390 invoking, 166–170 geometry and scrolling, document and element, constructor invocation, 170 390–396 indirect invocation, 170 determining element positioned at a point, method invocation, 167 393 invoking when document is ready, 466 document coordinates and viewport jQuery function (term), 528 coordinates, 390 jQuery( ) function ($ ( )), 527 element size, position, and overflow, 394 Math, 790 getting and setting element geometry, 534 memoization, 196 handling mousewheel events (example), names, 165 472–475 as namespaces, 178–180 querying geometry of an element, 392 nested, 309 scrolling, 394 partial application of, 194–196 Geoposition object, 935 processing arrays, 192–193 gesture and touch events, Safari on Apple properties, 186 iPhone and iPad, 456 length property, 186 GET method, 496 prototype, 186, 203 making HTTP request with form-encoded restrictions in secure subsets, 267 data, 503 returning arrays of values, destructuring no request body, 497 assignment with, 272 get( ) function, 563 setting event handler attributes to, 457 getAllResponseHeaders( ), XMLHttpRequest sharing between frames or windows, 358 object, 1015 shorthand for (expression closures), 282 getAttribute( ) and setAttribute( ) methods, toString( ) method, 189 Element object, 376 getAttribute( ) method, Element object, 906 Index | 1043
getAttributeNS( ), Element object, 907 getPrototypeOf( ) function, 135, 817 getBoundingClientRect( ), Element object, 392, getResponseHeader( ), XMLHttpRequest 396, 907 object, 1015 getClientRects( ), Element object, 393, 907 getScript( ) function, 561 getComputedStyle( ), Window object, 436, getSeconds( ) method, Date object, 748 1005 getSelection( ) method, Window object, 408 getContext( ) method, Canvas object, 630, getters and setters 636 jQuery, 531–537 getContext( ), Canvas object, 865 for CSS attributes, 532 getCurrentPosition( ), Geolocation object, 669, for CSS classes, 532 934 for element content, 534 getData( ), DataTransfer object, 478, 889 for element data, 536 getDate( ) method, Date object, 746 for element geometry, 534 getDay( ) method, Date object, 747 for HTML attributes, 531 getElementById( ), Document object, 352, 364, for HTML form values, 533 896 property, 128–130 selecting forms and form elements, 398 combining closures with, 183 getElementsByClassName( ) method legacy API for, 134 Document object, 368, 896 getTime( ) method, Date object, 748 Element object, 907 getTimezoneOffset( ) method, Date object, getElementsByName( ) method, 749 HTMLDocument object, 365 getUint16( ) method, DataView object, 890 getElementsByTagName( ) method getUint32( ) method, DataView object, 890 Document object, 366, 896 getUint8( ) method, DataView object, 890 selecting forms and form elements, 398 getUTCDate( ) method, Date object, 749 Element object, 907 getUTCDay( ) method, Date object, 750 getElementsByTagName( ), Document object, getUTCFullYear( ) method, Date object, 750 159 getUTCHours( ) method, Date object, 750 getElementsByTagNameNS( ) method getUTCMilliseconds( ) method, Date object, Document object, 896 750 Element object, 907 getUTCMinutes( ) method, Date object, 751 getFloat32( ) method, DataView object, 890 getUTCMonth( ) method, Date object, 751 getFloat64( ) method, DataView object, 890 getUTCSeconds( ) method, Date object, 751 getFullYear( ) method, Date object, 747 getYear( ) method, Date object, 751 getHours( ) method, Date object, 747 global functions, 25, 781 getImageData( ), CanvasRenderingContext2D, defined in Rhino, 290 661, 876 global object, 42, 781–784, 781 getInt16( ) method, DataView object, 890 properties referring to predefined JavaScript getInt32( ) method, DataView object, 890 objects, 782 getInt8( ) method, DataView object, 890 global property, RegExp object, 262, 832 getItem( ) method, Storage object, 988 global variables, 25, 31 getJSON( ) function, 561 avoiding by using functions as namespaces, getMilliseconds( ) method, Date object, 747 179 getMinutes( ) method, Date object, 748 avoiding creation of, in modules, 246 getModifierState( ), Event object, 920 as properties of global object, 55 getMonth( ) method, Date object, 748 restriction in secure subsets, 267 getOwnPropertyDescriptor( ) function, 131, use of element IDs as, 352 134, 815 globalAlpha property, 645, 646, 871 getOwnPropertyNames( ) function, 128, 816 1044 | Index
globalCompositeOperation property, 657, 869, Link object, 963 871 Location object, 343, 672, 964 globalEval( ) function, 572 WorkerLocation object, 1011 GMT (Greenwich Mean Time), 742 hashchange events, 672 go( ) method, History object, 345, 936 HashChangeEvent object, 935 Google hasOwnProperty( ) method, Object class, 125, Caja secure subset, 268 817 Closure library, 339 HAVE constants, MediaElement object, 965 promoting ability to load scripts from other HEAD method, HTTP request for link details sites, 313 with CORS, 512 V8 JavaScript engine and Node, 296 head property, Document object, 367, 893 Google Web Toolkit (GWT), 339 headers, HTTP request and response, 495 graded browser support, 329 checking Content-Type response header, gradients 501 CanvasGradient object, 866 Content-Length header, 508 gradients in Canvas, 645–648 CORS (Cross-Origin Resource Sharing) specifying for stroke or fill, 647 headers, 511 graphics, 613, 630 response headers, 498 (see also Canvas API) setting for POST request file upload, 506 scripting images, 614 setting POST request Content-Type header, SVG (Scalable Vector Graphics), 622–630 502 graphics APIs for web applications, 311 setting request header, 496 graphics attributes, canvas heading property, Geocoordinates object, 933 graphics state management utilities, 636 heading variable, 352 graphics attributes, Canvas API, 635 height and width style properties, 421, 425 graphics state (canvas), 635, 870 height property, 535 saving, 870, 879 (see also width and height properties) state management utilities, 636 ClientRect object, 880 grep( ) function, 572 IFrame object, 939 grep( ) method, jQuery, 579 height( ) method, jQuery, 535 group( ) method, Console object, 882 hexadecimal digits, specifying RGB colors, groupCollapsed( ) method, Console object, 427 882 hexadecimal values, 32 groupEnd( ) method, Console object, 883 hide( ) method, jQuery, 553, 555 grouping in regular expressions, 256 high property, Meter object, 973 GUIs (graphical user interfaces), creating Java higher-order functions, 193 GUI using JavaScript in Rhino combined with partial application, 196 (example), 293–296 history management in HTML5, 671–676 History object, 345, 936 H back( ), forward( ) and go( ) methods, 345 handler property, Event object, 544 pushState( ) method, 672 history management with (example), has( ) method, jQuery, 579 673–676 hasAttribute( ) method, Element object, 377, replaceState( ) method, 673 907 history property, Window object, 345, 1002 hasAttributeNS( ), Element object, 907 hit detection, 662–663 hasChildNodes( ), Node object, 978 hoisting, 54, 165 hasClass( ) method, jQuery, 532 host objects, 116 hasFocus( ) method, Document object, 896 host property hash property Index | 1045
Link object, 963 form-encoded HTTP requests, 502–507 Location object, 343, 964 FormControl objects, 929, 930 WorkerLocation object, 1011 FormData objects, 931 hostname property FormValidity objects, 932 Link object, 963 getting and setting values, 533 Location object, 343, 964 handler return value, preventing invalid WorkerLocation object, 1011 input, 462 :hover pseudoclass, 614 HTMLFormControlsCollection object, 938 hover( ) method, jQuery, 541, 545 new features in HTML5, 455 href attribute, <a> elements, 315, 367 push buttons, 401 href property select and option elements, 403 CSSStyleSheet object, 887 selecting forms and form elements, 398 Link object, 963 text fields, 402 Location object, 343, 964 toggle buttons, 402 WorkerLocation object, 1012 html( ) method, jQuery, 534 HSL (hue-saturation-value) color specification, HTML5, 667–716 427 APIs for web applications, 311 HSLA (hue-saturation-value-alpha) color application cache, 601 specification, 427 Blobs, 691–699 HTML classList property, 438, 533 attributes of elements, 375–378 client-side databases, 705–713 case-insensitive tag names, 366 cross-origin messaging, 676–680 element content as, 379 dataset attributes and dataset property, elements and attributes, 910–913 377 embedding JavaScript code using <script> DOMContentLoaded event, 465 tags, 9 drag and drop (DnD) API, 475 embedding JavaScript in, 311–317 editing commands, 410 escaping and inactivating HTML tags in event handlers directed at browser as a untrusted data, 337 whole, 458 event handlers, 315 events, 454 getting and setting attributes with jQuery, Filesystem API, 700–705 531 frames property as self-referential property, including CSS stylesheet in HTML page, 357 415 Geolocation API, 668–671 keeping HTML content separate from getElementsByClassName( ) method, 368 JavaScript behavior, 458 history management, 671–676 not case-sensitive, 21 innerHTML and outerHTML properties, <script> element, 309 379 scripting document content, 9 insertAdjacentHTML( ) method, 379 String class methods, 836 Offline Web Applications API, 588 strings, single- and double-quoted, 37 placeholder attribute, text fields, 402 using JavaScript to script content, 10 sandbox attribute for <iframe> element, <html> elements, manifest attribute, 601 337 HTML forms, 397–404 SVG markup appearing directly in HTML elements, 397 files, 624 events, 450 typed arrays and ArrayBuffers, 687–691 form and element event handlers, 400 “web workers”, 322 form and element properties, 399 Web Workers specification, 680–687 Form objects, 927–929 WebSocket API, 713–716 1046 | Index
WindowProxy object, 359 format control characters and, 22 HTMLCollection object, 367, 937 in labeled statements, 102 form elements, 398 in property access expressions, 60 overview of, 367 identity operator (see operators; strict equality HTMLDocument object, 363 operator) (see also Document object) if statements, 92 getElementsByName( ) method, 365 in array comprehensions, 281 images, forms, and links properties, 367 in else if statements, 94 HTMLElement object, 363 nested, with else clauses, 93 (see also Element object) <iframe> elements, 334 properties mirroring HTML attributes of Ajax transport with, 492 elements, 375 browsing history and, 345 representing HTML elements in documents, contentWindow property, 357 351 deleting to close frames, 356 text property, 314 document properties for, referring to htmlFor property Window object, 366 Label object, 962 making document editable in, 409 Output object, 981 name attribute, 354 HTMLOptionsCollection object, 938 nested documents in HTML documents, HTTP, 713 353 attributes of HTML elements, 375 returning contents of, 581 client utilities module in Node (example), sandbox attribute in HTML5, 337 302–304 using in history management, 346 HTTP server in Node (example), 300–302 with name and id attribute, becoming value scripted, 491–521 of global variable, 353 using <script> elements, 513–515 IFrame object, 939 using Comet with Server-Sent Events, ignoreCase property, RegExp object, 262, 832 515–521 ImageData object, 661 using XMLHttpRequest, 494–513 ImageData objects, 941 HTTP methods, 496 copying onto the canvas, 878 hyperlinks, 316 creating, 874 bookmarking destination of, 317 data property, array of bytes, 688 Link objects, 962 passing to worker via postMessage( ), 684 onclick event handler, 401 images hyphenated attribute names, 377 displaying dropped image files with Blob URLs, 695 I drawing in canvas, 655–657, 868 i (case-insensitive matching) in regular extracting canvas content as, 656 Image object, 940 expressions, 259 scripting, 614 I/O unobtrusive image rollovers, 615 asynchronous, scripting with Node, 296– Web Worker for image processing 304 (example), 684 HTTP client (example), 302–304 images property, HTMLDocument object, HTTP server (example), 300–302 367 id attribute, HTML elements, 351 <img> elements, 614 id property, Element object, 904 Ajax transport and, 492 IDBRange object, 706 displaying SVG images, 622 identifiers immutable classes, defining, 239–241 defined, 23 Index | 1047
immutable objects, 137, 814, 819 inline styles, scripting, 431–435 immutable types, 31 CSS animations, 433–435 implementation property, Document, 893 setting while querying computed styles, importNode( ), Document object, 382, 896 436 importScripts( ), WorkerGlobalScope object, innerHeight and innerWidth properties, 682, 1010 Window object, 1002 in operator, 62, 74 innerHTML property, Element object, 379, testing for inherited or noninherited 386, 904 properties, 125 streaming API for, 407 inArray( ) method, 572 use in jQuery to get element content, 534 increment expression (for loops), 98 using to implement outerHTML, 384 indeterminate property, Input object, 943 innerText property, Element object, 380 index property, Option object, 980 innerWidth( ) and innerHeight( ) methods, index( ) method, jQuery, 530 jQuery, 535 IndexedDB API, 588, 705–713 <input> elements, buttons defined as, 401 database of U.S. postal codes (example), file uploads with, 505 708–713 input events indexes device-dependent and -independent, 448 array, 141 triggered on text input form elements, 450 indexOf ( ) and lastIndexOf ( ) methods, Input object, 942 157 methods, 945 object property names versus, 143 properties, 942 zero-based, string and array, 36 input variable, 352 indexOf( ) method inputMethod, Event object, 453, 481, 920 Array object, 157, 727 insertAdjacentHTML( ), Element object, 379, String object, 840 908 inequality operators (see ! (exclamation mark), implementing using innerHTML and under Symbols) DocumentFragment, 386 infinite loops, 99 insertAfter( ) method, jQuery, 538 Infinity property, 784 insertBefore( ) method, jQuery, 538 infinity values, 33 insertBefore( ) method, Node object, 383, 978 info( ) method, Console object, 883 insertCell( ) method, TableRow object, 992 inheritance insertData( ) method accessor properties, 130 Comment node, 881 classes and prototypes, 200 Text node, 993 creating new object that inherits from insertion and deletion methods in jQuery, 953 prototype, 119 insertRow( ) method enumeration of properties and, 126 Table object, 991 favoring composition over, in object- TableSection object, 993 oriented design, 233 insertRule( ), CSSStyleSheet object, 441, 888 object properties, 122 inspect( ), ConsoleCommandLine, 884 prototype constructor as prototype for new instance fields and methods (Java classes), 205 object, 201 instance objects, 205 subclasses, 230 instanceof operator, 62, 75 inherited properties, 116 determining class of an object, 210 initEvent( ) method, Event object, 919 inability to distinguish array type, 158 initialize expression (for loops), 98 isPrototypeOf( ) method and, 135 initializer expressions, 5, 58 not working across windows, 359 initialTime, MediaElement object, 618, 967 1048 | Index
using with constructors to test objects’ class userData persistence, 599–601 membership, 203 XMLHttpRequest in IE 6, 494 working with Java objects and classes in interpreters, 3 Rhino, 291 JavaScript versions, 269 instances, 199 support for E4X, 283 arrays of, sorting, 224 support for JavaScript extensions, 265 constructor property, 204 invocation context, 163 creating and initializing with factory invocation expressions, 61 function, 200 function invocation, 167 factory methods returning, 227 precedence, 65 Int16Array class, 996 invocation order, event handlers, 462 Int32Array class, 996 invoking functions, 166–170 Int8Array class, 688, 996 constructor invocation, 170 integer literals, 32 event handlers, 460–465 integers, 31 indirectly, 170 interacting windows, JavaScript in, 358 jQuery( ) function, 526 interfaces (see UI (user interface)) method invocation, 167 Internet Explorer (IE) iPhone and iPad, gesture and touch events, <canvas> element, 630 456 clientInformation property, Window is( ) method, jQuery, 530, 533 object, 346 isArray( ) function, 573 computed styles, 437 isArray( ) method, Array object, 157, 160 conditional comments in, 331 isContentEditable, Element object, 904 CSS box model, 425 isDefaultNamespace( ) method, Node object, current version, 327 978 drag and drop (DnD) API, 475 isEmptyObject( ) function, 573 event model isEqualNode( ) method, Node object, 978 attachEvent( ) and addEventListener( ) isExtensible( ) function, 137, 818 methods, 321 isFinite( ) function, 34, 784 attachEvent( ) and detachEvent( ) isFrozen( ) function, 137, 819 methods, 459, 923 isFunction( ) function, 191, 573 event capturing and, 463 isNaN( ) function, 34 form events, 450 isPlainObject( ) function, 573 filter property, 428 isPointInPath( ), CanvasRenderingContext2D, innerText property instead of textContent, 662, 877 380 isPrototypeOf( ) method, 135, 819 nonbubbling mouse events, 452 isSameNode( ) method, Node object, 978 not supporting isSealed( ) function, 820 getElementsByClassName( ), 369 isTrusted property, Event object, 916 propertychange event, using to detect text item( ) method input, 484 DOMTokenList object, 902 querying selected text, 408 HTMLCollection object, 368, 937 removing script tags and other executable HTMLOptionsCollection object, 939 content in IE8, 337 NodeList object, 368, 980 rules property instead of cssRules, 441 Select element, 987 timer methods, 342 items property, DataTransfer object, 478, 888 use of callable host objects rather than native iterable objects, 275 Function objects, 191 iteration userData API, 588 arrays, 146–148 Index | 1049
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301
- 302
- 303
- 304
- 305
- 306
- 307
- 308
- 309
- 310
- 311
- 312
- 313
- 314
- 315
- 316
- 317
- 318
- 319
- 320
- 321
- 322
- 323
- 324
- 325
- 326
- 327
- 328
- 329
- 330
- 331
- 332
- 333
- 334
- 335
- 336
- 337
- 338
- 339
- 340
- 341
- 342
- 343
- 344
- 345
- 346
- 347
- 348
- 349
- 350
- 351
- 352
- 353
- 354
- 355
- 356
- 357
- 358
- 359
- 360
- 361
- 362
- 363
- 364
- 365
- 366
- 367
- 368
- 369
- 370
- 371
- 372
- 373
- 374
- 375
- 376
- 377
- 378
- 379
- 380
- 381
- 382
- 383
- 384
- 385
- 386
- 387
- 388
- 389
- 390
- 391
- 392
- 393
- 394
- 395
- 396
- 397
- 398
- 399
- 400
- 401
- 402
- 403
- 404
- 405
- 406
- 407
- 408
- 409
- 410
- 411
- 412
- 413
- 414
- 415
- 416
- 417
- 418
- 419
- 420
- 421
- 422
- 423
- 424
- 425
- 426
- 427
- 428
- 429
- 430
- 431
- 432
- 433
- 434
- 435
- 436
- 437
- 438
- 439
- 440
- 441
- 442
- 443
- 444
- 445
- 446
- 447
- 448
- 449
- 450
- 451
- 452
- 453
- 454
- 455
- 456
- 457
- 458
- 459
- 460
- 461
- 462
- 463
- 464
- 465
- 466
- 467
- 468
- 469
- 470
- 471
- 472
- 473
- 474
- 475
- 476
- 477
- 478
- 479
- 480
- 481
- 482
- 483
- 484
- 485
- 486
- 487
- 488
- 489
- 490
- 491
- 492
- 493
- 494
- 495
- 496
- 497
- 498
- 499
- 500
- 501
- 502
- 503
- 504
- 505
- 506
- 507
- 508
- 509
- 510
- 511
- 512
- 513
- 514
- 515
- 516
- 517
- 518
- 519
- 520
- 521
- 522
- 523
- 524
- 525
- 526
- 527
- 528
- 529
- 530
- 531
- 532
- 533
- 534
- 535
- 536
- 537
- 538
- 539
- 540
- 541
- 542
- 543
- 544
- 545
- 546
- 547
- 548
- 549
- 550
- 551
- 552
- 553
- 554
- 555
- 556
- 557
- 558
- 559
- 560
- 561
- 562
- 563
- 564
- 565
- 566
- 567
- 568
- 569
- 570
- 571
- 572
- 573
- 574
- 575
- 576
- 577
- 578
- 579
- 580
- 581
- 582
- 583
- 584
- 585
- 586
- 587
- 588
- 589
- 590
- 591
- 592
- 593
- 594
- 595
- 596
- 597
- 598
- 599
- 600
- 601
- 602
- 603
- 604
- 605
- 606
- 607
- 608
- 609
- 610
- 611
- 612
- 613
- 614
- 615
- 616
- 617
- 618
- 619
- 620
- 621
- 622
- 623
- 624
- 625
- 626
- 627
- 628
- 629
- 630
- 631
- 632
- 633
- 634
- 635
- 636
- 637
- 638
- 639
- 640
- 641
- 642
- 643
- 644
- 645
- 646
- 647
- 648
- 649
- 650
- 651
- 652
- 653
- 654
- 655
- 656
- 657
- 658
- 659
- 660
- 661
- 662
- 663
- 664
- 665
- 666
- 667
- 668
- 669
- 670
- 671
- 672
- 673
- 674
- 675
- 676
- 677
- 678
- 679
- 680
- 681
- 682
- 683
- 684
- 685
- 686
- 687
- 688
- 689
- 690
- 691
- 692
- 693
- 694
- 695
- 696
- 697
- 698
- 699
- 700
- 701
- 702
- 703
- 704
- 705
- 706
- 707
- 708
- 709
- 710
- 711
- 712
- 713
- 714
- 715
- 716
- 717
- 718
- 719
- 720
- 721
- 722
- 723
- 724
- 725
- 726
- 727
- 728
- 729
- 730
- 731
- 732
- 733
- 734
- 735
- 736
- 737
- 738
- 739
- 740
- 741
- 742
- 743
- 744
- 745
- 746
- 747
- 748
- 749
- 750
- 751
- 752
- 753
- 754
- 755
- 756
- 757
- 758
- 759
- 760
- 761
- 762
- 763
- 764
- 765
- 766
- 767
- 768
- 769
- 770
- 771
- 772
- 773
- 774
- 775
- 776
- 777
- 778
- 779
- 780
- 781
- 782
- 783
- 784
- 785
- 786
- 787
- 788
- 789
- 790
- 791
- 792
- 793
- 794
- 795
- 796
- 797
- 798
- 799
- 800
- 801
- 802
- 803
- 804
- 805
- 806
- 807
- 808
- 809
- 810
- 811
- 812
- 813
- 814
- 815
- 816
- 817
- 818
- 819
- 820
- 821
- 822
- 823
- 824
- 825
- 826
- 827
- 828
- 829
- 830
- 831
- 832
- 833
- 834
- 835
- 836
- 837
- 838
- 839
- 840
- 841
- 842
- 843
- 844
- 845
- 846
- 847
- 848
- 849
- 850
- 851
- 852
- 853
- 854
- 855
- 856
- 857
- 858
- 859
- 860
- 861
- 862
- 863
- 864
- 865
- 866
- 867
- 868
- 869
- 870
- 871
- 872
- 873
- 874
- 875
- 876
- 877
- 878
- 879
- 880
- 881
- 882
- 883
- 884
- 885
- 886
- 887
- 888
- 889
- 890
- 891
- 892
- 893
- 894
- 895
- 896
- 897
- 898
- 899
- 900
- 901
- 902
- 903
- 904
- 905
- 906
- 907
- 908
- 909
- 910
- 911
- 912
- 913
- 914
- 915
- 916
- 917
- 918
- 919
- 920
- 921
- 922
- 923
- 924
- 925
- 926
- 927
- 928
- 929
- 930
- 931
- 932
- 933
- 934
- 935
- 936
- 937
- 938
- 939
- 940
- 941
- 942
- 943
- 944
- 945
- 946
- 947
- 948
- 949
- 950
- 951
- 952
- 953
- 954
- 955
- 956
- 957
- 958
- 959
- 960
- 961
- 962
- 963
- 964
- 965
- 966
- 967
- 968
- 969
- 970
- 971
- 972
- 973
- 974
- 975
- 976
- 977
- 978
- 979
- 980
- 981
- 982
- 983
- 984
- 985
- 986
- 987
- 988
- 989
- 990
- 991
- 992
- 993
- 994
- 995
- 996
- 997
- 998
- 999
- 1000
- 1001
- 1002
- 1003
- 1004
- 1005
- 1006
- 1007
- 1008
- 1009
- 1010
- 1011
- 1012
- 1013
- 1014
- 1015
- 1016
- 1017
- 1018
- 1019
- 1020
- 1021
- 1022
- 1023
- 1024
- 1025
- 1026
- 1027
- 1028
- 1029
- 1030
- 1031
- 1032
- 1033
- 1034
- 1035
- 1036
- 1037
- 1038
- 1039
- 1040
- 1041
- 1042
- 1043
- 1044
- 1045
- 1046
- 1047
- 1048
- 1049
- 1050
- 1051
- 1052
- 1053
- 1054
- 1055
- 1056
- 1057
- 1058
- 1059
- 1060
- 1061
- 1062
- 1063
- 1064
- 1065
- 1066
- 1067
- 1068
- 1069
- 1070
- 1071
- 1072
- 1073
- 1074
- 1075
- 1076
- 1077
- 1078
- 1079
- 1080
- 1081
- 1 - 50
- 51 - 100
- 101 - 150
- 151 - 200
- 201 - 250
- 251 - 300
- 301 - 350
- 351 - 400
- 401 - 450
- 451 - 500
- 501 - 550
- 551 - 600
- 601 - 650
- 651 - 700
- 701 - 750
- 751 - 800
- 801 - 850
- 851 - 900
- 901 - 950
- 951 - 1000
- 1001 - 1050
- 1051 - 1081
Pages: