Prototype

An object-oriented JavaScript framework

Prototype is a JavaScript framework that aims to ease development of dynamic web applications. It offers a familiar class-style OO framework, extensive Ajax support, higher-order programming constructs, and easy DOM manipulation.

Targeted platforms

Prototype currently targets the following platforms:

  • Microsoft Internet Explorer for Windows, version 6.0 and higher
  • Mozilla Firefox 1.5 and higher
  • Apple Safari 2.0.4 and higher
  • Opera 9.25 and higher
  • Chrome 1.0 and higher

Using Prototype

To use Prototype in your application, download the latest release from the Prototype web site (http://prototypejs.org/download) and copy dist/prototype.js to a suitable location. Then include it in your HTML like so:

<script type="text/javascript" src="/path/to/prototype.js"></script>

Building Prototype from source

prototype.js is a composite file generated from many source files in the src/ directory. To build Prototype, you'll need:

  • a copy of the Prototype source tree, either from a distribution tarball or from the Git repository (see below)
  • Ruby 1.8.2 or higher (http://www.ruby-lang.org/)
  • Rake--Ruby Make (http://rake.rubyforge.org/)
  • RDoc, if your Ruby distribution does not include it

From the root Prototype directory,

  • rake dist will preprocess the Prototype source using Sprockets and generate the composite dist/prototype.js.
  • rake package will create a distribution tarball in the pkg/ directory.

Contributing to Prototype

Check out the Prototype source with

$ git clone git://github.com/sstephenson/prototype.git
$ cd prototype
$ git submodule init
$ git submodule update vendor/sprockets vendor/pdoc vendor/unittest_js

Find out how to contribute: http://prototypejs.org/contribute.

Documentation

Please see the online Prototype API: http://api.prototypejs.org.

Sections

  • ajax

    Prototype's APIs around the XmlHttpRequest object.

  • dom

    Extensions to DOM elements, plus other utilities for DOM traversal and modification.

  • language

    Additions to JavaScript's "standard library" and extensions to built-in JavaScript objects.

Prototype

Description

The Prototype namespace provides fundamental information about the Prototype library you're using, as well as a central repository for default iterators or functions.

We say "namespace," because the Prototype object is not intended for instantiation, nor for mixing in other objects. It's really just... a namespace.

Your version of Prototype

Your scripts can check against a particular version of Prototype by examining Prototype.Version, which is a version String (e.g. "<%= PROTOTYPE_VERSION %>"). The famous script.aculo.us library does this at load time to ensure it's being used with a reasonably recent version of Prototype, for instance.

Browser features

Prototype also provides a (nascent) repository of Prototype.BrowserFeatures, which it then uses here and there in its source code. The idea is, first, to make Prototype's source code more readable; and second, to centralize whatever scripting trickery might be necessary to detect the browser feature, in order to ease maintenance.

Default iterators and functions

Numerous methods in Prototype objects (most notably the Enumerable module) let the user pass in a custom iterator, but make it optional by defaulting to an "identity function" (an iterator that just returns its argument, untouched). This is the Prototype.K function, which you'll see referred to in many places.

Many methods also take it easy by protecting themselves against missing methods here and there, reverting to empty functions when a supposedly available method is missing. Such a function simply ignores its potential arguments, and does nothing whatsoever (which is, oddly enough, blazing fast). The quintessential empty function sits, unsurprisingly, at Prototype.emptyFunction (note the lowercase first letter).

Namespaces

  • Prototype.Browser

    A collection of [[Boolean]] values indicating the browser which is currently in use. Available properties are IE, Opera, WebKit, MobileSafari and Gecko.

  • Prototype.BrowserFeatures

    A collection of [[Boolean]] values indicating the presence of specific browser features.

  • Prototype.Selector

    A namespace that acts as a wrapper around the choosen selector engine (Sizzle by default).

Class methods

Class properties

Prototype.Browser

Description

A collection of [[Boolean]] values indicating the browser which is currently in use. Available properties are IE, Opera, WebKit, MobileSafari and Gecko.

Example

Prototype.Browser.WebKit;
//-> true, when executed in any WebKit-based browser.

Prototype.BrowserFeatures

Description

A collection of [[Boolean]] values indicating the presence of specific browser features.

Prototype.BrowserFeatures.ElementExtensions

    • Prototype.BrowserFeatures.ElementExtensions
      • Boolean

Used internally to detect if the browser supports extending html element prototypes.

Prototype.BrowserFeatures.SelectorsAPI

    • Prototype.BrowserFeatures.SelectorsAPI
      • Boolean

Used internally to detect if the browser supports the NodeSelector API.

Prototype.BrowserFeatures.XPath

    • Prototype.BrowserFeatures.XPath
      • Boolean

Used internally to detect if the browser supports DOM Level 3 XPath.

Prototype.Selector

Description

A namespace that acts as a wrapper around the choosen selector engine (Sizzle by default).

Prototype.Selector.extendElement

    • Prototype.Selector.extendElement(element)

Prototype.Selector.extendElements

    • Prototype.Selector.extendElements(elements)
    • elements
      • Enumerable
    • a collection of DOM elements.

If necessary, extends the elements contained in elements and returns elements untouched. This is provided as a convenience method for selector engine wrapper implementors.

Prototype.Selector.find

    • Prototype.Selector.find(elements, expression[, index = 0])
    • elements
      • Enumerable
    • a collection of DOM elements.

    • expression
      • String
    • A CSS selector.

    • index
      • Number
    • Numeric index of the match to return, defaults to 0.

Filters the given collection of elements with expression and returns the first matching element (or the indexth matching element if index is specified).

Prototype.Selector.match

    • Prototype.Selector.match(element, expression)
      • Boolean
    • element
      • Element
    • a DOM element.

    • expression
      • String
    • A CSS selector.

Tests whether element matches the CSS selector.

Prototype.Selector.select

    • Prototype.Selector.select(expression[, root = "document"])
    • expression
      • String
    • A CSS selector.

    • root
      • Element
      • document
    • A "scope" to search within. All results will be descendants of this node.

Searches root for elements that match the provided CSS selector and returns an array of extended Element objects.

Prototype.emptyFunction

    • Prototype.emptyFunction([argument...])
      • undefined
    • argument
      • Object
    • Optional arguments

The Prototype.emptyFunction does nothing... and returns nothing!

It is used thoughout the framework to provide a fallback function in order to cut down on conditionals. Typically you'll find it as a default value for optional callback functions.

Prototype.K

    • Prototype.K(argument)
      • argument
    • argument
      • Object
    • Optional argument...

Prototype.K is Prototype's very own identity function, i.e. it returns its argument untouched.

This is used throughout the framework, most notably in the Enumerable module as a default value for iterators.

Examples
Prototype.K('hello world!');
// -> 'hello world!'

Prototype.K(200);
// -> 200

Prototype.K(Prototype.K);
// -> Prototype.K

Prototype.Version

The version of the Prototype library you are using (e.g. "<%= PROTOTYPE_VERSION %>").

Ajax section

Description

Prototype's APIs around the XmlHttpRequest object.

The Prototype framework enables you to deal with Ajax calls in a manner that is both easy and compatible with all modern browsers.

Actual requests are made by creating instances of Ajax.Request.

Request headers

The following headers are sent with all Ajax requests (and can be overridden with the requestHeaders option described below):

  • X-Requested-With is set to XMLHttpRequest.
  • X-Prototype-Version is set to Prototype's current version (e.g., <%= PROTOTYPE_VERSION %>).
  • Accept is set to text/javascript, text/html, application/xml, text/xml, * / *
  • Content-type is automatically determined based on the contentType and encoding options.
Ajax options

All Ajax classes share a common set of options and callbacks. Callbacks are called at various points in the life-cycle of a request, and always feature the same list of arguments.

Common options
  • asynchronous ([[Boolean]]; default true): Determines whether XMLHttpRequest is used asynchronously or not. Synchronous usage is strongly discouraged — it halts all script execution for the duration of the request and blocks the browser UI.
  • contentType (String; default application/x-www-form-urlencoded): The Content-type header for your request. Change this header if you want to send data in another format (like XML).
  • encoding (String; default UTF-8): The encoding for the contents of your request. It is best left as-is, but should weird encoding issues arise, you may have to tweak this.
  • method (String; default post): The HTTP method to use for the request. The other common possibility is get. Abiding by Rails conventions, Prototype also reacts to other HTTP verbs (such as put and delete) by submitting via post and adding a extra _method parameter with the originally-requested method.
  • parameters (String): The parameters for the request, which will be encoded into the URL for a get method, or into the request body for the other methods. This can be provided either as a URL-encoded string, a Hash, or a plain Object.
  • postBody (String): Specific contents for the request body on a post method. If it is not provided, the contents of the parameters option will be used instead.
  • requestHeaders (Object): A set of key-value pairs, with properties representing header names.
  • evalJS ([[Boolean]] | String; default true): Automatically evals the content of Ajax.Response#responseText and populates Ajax.Response#responseJSON with it if the Content-type returned by the server is set to application/json. If the request doesn't obey same-origin policy, the content is sanitized before evaluation. If you need to force evalutation, pass 'force'. To prevent it altogether, pass false.
  • sanitizeJSON ([[Boolean]]; default is false for same-origin requests, true otherwise): Sanitizes the contents of Ajax.Response#responseText before evaluating it.
Common callbacks

When used on individual instances, all callbacks (except onException) are invoked with two parameters: the Ajax.Response object and the result of evaluating the X-JSON response header, if any (can be null).

For another way of describing their chronological order and which callbacks are mutually exclusive, see Ajax.Request.

  • onCreate: Triggered when the Ajax.Request object is initialized. This is after the parameters and the URL have been processed, but before opening the connection via the XHR object.
  • onUninitialized (Not guaranteed): Invoked just after the XHR object is created.
  • onLoading (Not guaranteed): Triggered when the underlying XHR object is being setup, and its connection opened.
  • onLoaded (Not guaranteed): Triggered once the underlying XHR object is setup, the connection is open, and it is ready to send its actual request.
  • onInteractive (Not guaranteed): Triggered whenever the requester receives a part of the response (but not the final part), should it be sent in several packets.
  • onSuccess: Invoked when a request completes and its status code is undefined or belongs in the 2xy family. This is skipped if a code-specific callback is defined (e.g., on200), and happens before onComplete.
  • onFailure: Invoked when a request completes and its status code exists but is not in the 2xy family. This is skipped if a code-specific callback is defined (e.g. on403), and happens before onComplete.
  • onXYZ (with XYZ representing any HTTP status code): Invoked just after the response is complete if the status code is the exact code used in the callback name. Prevents execution of onSuccess and onFailure. Happens before onComplete.
  • onException: Triggered whenever an XHR error arises. Has a custom signature: the first argument is the requester (i.e. an Ajax.Request instance), and the second is the exception object.
  • onComplete: Triggered at the very end of a request's life-cycle, after the request completes, status-specific callbacks are called, and possible automatic behaviors are processed. Guaranteed to run regardless of what happened during the request.

Namespaces

Ajax

Namespaces

  • Ajax.Responders

    A repository of global listeners notified about every step of Prototype-based Ajax requests.

Classes

  • Ajax.PeriodicalUpdater

    Periodically performs an Ajax request and updates a container's contents based on the response text.

  • Ajax.Request

    Initiates and processes an Ajax request.

  • Ajax.Response

    A wrapper class around XmlHttpRequest for dealing with HTTP responses of Ajax requests.

  • Ajax.Updater

    A class that performs an Ajax request and updates a container's contents with the contents of the response.

Class properties

Ajax.PeriodicalUpdater

Description

Periodically performs an Ajax request and updates a container's contents based on the response text.

Ajax.PeriodicalUpdater behaves like Ajax.Updater, but performs the update at a prescribed interval, rather than only once. (Note that it is not a subclass of Ajax.Updater; it's a wrapper around it.)

This class addresses the common need of periodical update, as required by all sorts of "polling" mechanisms (e.g., an online chatroom or an online mail client).

The basic idea is to run a regular Ajax.Updater at regular intervals, keeping track of the response text so it can (optionally) react to receiving the exact same response consecutively.

Additional options

Ajax.PeriodicalUpdater features all the common options and callbacks described in the Ajaxplus those added by Ajax.Updater.

It also provides two new options:

  • frequency (Number; default is 2): How long, in seconds, to wait between the end of one request and the beginning of the next.
  • decay (Number; default is 1): The rate at which the frequency grows when the response received is exactly the same as the previous. The default of 1 means frequency will never grow; override the default if a stale response implies it's worthwhile to poll less often. If decay is set to 2, for instance, frequency will double (2 seconds, 4 seconds, 8 seconds...) each consecutive time the result is the same; when the result is different once again, frequency will revert to its original value.
Disabling and re-enabling a Ajax.PeriodicalUpdater

You can hit the brakes on a running Ajax.PeriodicalUpdater by calling Ajax.PeriodicalUpdater#stop. If you wish to re-enable it later, call Ajax.PeriodicalUpdater#start.

Instance methods

Ajax.PeriodicalUpdater.new

    • new Ajax.PeriodicalUpdater(container, url[, options])
    • container
      • String
      • Element
    • The DOM element whose contents to update as a result of the Ajax request. Can be a DOM node or a string that identifies a node's ID.

    • url
      • String
    • The URL to fetch. When the same-origin policy is in effect (as it is in most cases), url must be a relative URL or an absolute URL that starts with a slash (i.e., it must not begin with http).

    • options
      • Object
    • Configuration for the request. See the Ajax for more information.

Creates a new Ajax.PeriodicalUpdater.

Periodically performs an AJAX request and updates a container's contents based on the response text. Offers a mechanism for "decay," which lets it
trigger at widening intervals while the response is unchanged.

This object addresses the common need of periodical update, which is used by all sorts of "polling" mechanisms (e.g. in an online chatroom or an online mail client).

The basic idea is to run a regular Ajax.Updater at regular intervals, monitoring changes in the response text if the decay option (see below) is active.

Additional options

Ajax.PeriodicalUpdater features all the common options and callbacks (see the Ajax for more information), plus those added by Ajax.Updater. It also provides two new options that deal with the original period, and its decay rate (how Rocket Scientist does that make us sound, uh?!).

<table> <thead> <tr> <th>Option</th> <th>Default</th> <th>Description</th> </tr> </thead> <tbody> <tr> <th><code>frequency</code></th> <td><code>2</code></td> <td>Okay, this is not a frequency (e.g 0.5Hz), but a period (i.e. a number of seconds). Don't kill me, I didn't write this one! This is the minimum interval at which AJAX requests are made. You don't want to make it too short (otherwise you may very well end up with multiple requests in parallel, if they take longer to process and return), but you technically can provide a number below one, e.g. 0.75 second.</td> </tr> <tr> <th><code>decay</code></th> <td>1</td> <td>This controls the rate at which the request interval grows when the response is unchanged. It is used as a multiplier on the current period (which starts at the original value of the <code>frequency</code> parameter). Every time a request returns an unchanged response text, the current period is multiplied by the decay. Therefore, the default value means regular requests (no change of interval). Values higher than one will yield growing intervals. Values below one are dangerous: the longer the response text stays the same, the more often you'll check, until the interval is so short your browser is left with no other choice than suicide. Note that, as soon as the response text <em>does</em> change, the current period resets to the original one.</td> </tr> </tbody> </table>

To better understand decay, here is a small sequence of calls from the following example:

new Ajax.PeriodicalUpdater('items', '/items', {
  method: 'get', frequency: 3, decay: 2
});

<table id="decayTable"> <thead> <tr> <th>Call#</th> <th>When?</th> <th>Decay before</th> <th>Response changed?</th> <th>Decay after</th> <th>Next period</th> <th>Comments</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>00:00</td> <td>2</td> <td>n/a</td> <td>1</td> <td>3</td> <td>Response is deemed changed, since there is no prior response to compare to!</td> </tr> <tr> <td>2</td> <td>00:03</td> <td>1</td> <td>yes</td> <td>1</td> <td>3</td> <td>Response did change again: we "reset" to 1, which was already the decay.</td> </tr> <tr> <td>3</td> <td>00:06</td> <td>1</td> <td>no</td> <td>2</td> <td>6</td> <td>Response didn't change: decay augments by the <code>decay</code> option factor: we're waiting longer now…</td> </tr> <tr> <td>4</td> <td>00:12</td> <td>2</td> <td>no</td> <td>4</td> <td>12</td> <td>Still no change, doubling again.</td> </tr> <tr> <td>5</td> <td>00:24</td> <td>4</td> <td>no</td> <td>8</td> <td>24</td> <td>Jesus, is this thing going to change or what?</td> </tr> <tr> <td>6</td> <td>00:48</td> <td>8</td> <td>yes</td> <td>1</td> <td>3</td> <td>Ah, finally! Resetting decay to 1, and therefore using the original period.</td> </tr> </tbody> </table>

Disabling and re-enabling a Ajax.PeriodicalUpdater

You can pull the brake on a running Ajax.PeriodicalUpdater by simply calling its stop method. If you wish to re-enable it later, just call its start method. Both take no argument.

Beware! Not a specialization!

Ajax.PeriodicalUpdater is not a specialization of Ajax.Updater, despite its name. When using it, do not expect to be able to use methods normally provided by Ajax.Request and "inherited" by Ajax.Updater, such as evalJSON or getHeader. Also the onComplete callback is hijacked to be used for update management, so if you wish to be notified of every successful request, use onSuccess instead (beware: it will get called before the update is performed).

Ajax.PeriodicalUpdater#start

    • Ajax.PeriodicalUpdater#start()
      • undefined

Starts the periodical updater (if it had previously been stopped with Ajax.PeriodicalUpdater#stop).

Ajax.PeriodicalUpdater#stop

    • Ajax.PeriodicalUpdater#stop()
      • undefined

Stops the periodical updater.

Also calls the onComplete callback, if one has been defined.

Ajax.Request

Description

Initiates and processes an Ajax request.

Ajax.Request is a general-purpose class for making HTTP requests which handles the life-cycle of the request, handles the boilerplate, and lets you plug in callback functions for your custom needs.

In the optional options hash, you usually provide an onComplete and/or onSuccess callback, unless you're in the edge case where you're getting a JavaScript-typed response, that will automatically be eval'd.

For a full list of common options and callbacks, see "Ajax options" heading of the Ajax.

A basic example
new Ajax.Request('/your/url', {
  onSuccess: function(response) {
    // Handle the response content...
  }
});
Request life-cycle

Underneath our nice requester objects lies, of course, XMLHttpRequest. The defined life-cycle is as follows:

  1. Created
  2. Initialized
  3. Request sent
  4. Response being received (can occur many times, as packets come in)
  5. Response received, request complete

As you can see under the "Ajax options" heading of the Ajax, Prototype's AJAX objects define a whole slew of callbacks, which are triggered in the following order:

  1. onCreate (this is actually a callback reserved to Ajax.Responders)
  2. onUninitialized (maps on Created)
  3. onLoading (maps on Initialized)
  4. onLoaded (maps on Request sent)
  5. onInteractive (maps on Response being received)
  6. onXYZ (numerical response status code), onSuccess or onFailure (see below)
  7. onComplete

The two last steps both map on Response received, in that order. If a status-specific callback is defined, it gets invoked. Otherwise, if onSuccess is defined and the response is deemed a success (see below), it is invoked. Otherwise, if onFailure is defined and the response is not deemed a sucess, it is invoked. Only after that potential first callback is onComplete called.

A note on portability

Depending on how your browser implements XMLHttpRequest, one or more callbacks may never be invoked. In particular, onLoaded and onInteractive are not a 100% safe bet so far. However, the global onCreate, onUninitialized and the two final steps are very much guaranteed.

onSuccess and onFailure, the under-used callbacks

Way too many people use Ajax.Request in a similar manner to raw XHR, defining only an onComplete callback even when they're only interested in "successful" responses, thereby testing it by hand:

// This is too bad, there's better!
new Ajax.Request('/your/url', {
  onComplete: function(response) {
    if (200 == response.status)
      // yada yada yada
  }
});

First, as described below, you could use better "success" detection: success is generally defined, HTTP-wise, as either no response status or a "2xy" response status (e.g., 201 is a success, too). See the example below.

Second, you could dispense with status testing altogether! Prototype adds callbacks specific to success and failure, which we listed above. Here's what you could do if you're only interested in success, for instance:

new Ajax.Request('/your/url', {
  onSuccess: function(response) {
      // yada yada yada
  }
});
Automatic JavaScript response evaluation

If an Ajax request follows the same-origin policy and its response has a JavaScript-related Content-type, the content of the responseText property will automatically be passed to eval.

In other words: you don't even need to provide a callback to leverage pure-JavaScript Ajax responses. This is the convention that drives Rails's RJS.

The list of JavaScript-related MIME-types handled by Prototype is:

  • application/ecmascript
  • application/javascript
  • application/x-ecmascript
  • application/x-javascript
  • text/ecmascript
  • text/javascript
  • text/x-ecmascript
  • text/x-javascript

The MIME-type string is examined in a case-insensitive manner.

Methods you may find useful

Instances of the Ajax.Request object provide several methods that come in handy in your callback functions, especially once the request is complete.

Is the response a successful one?

The Ajax.Request#success method examines the XHR object's status property and follows general HTTP guidelines: unknown status is deemed successful, as is the whole 2xy status code family. It's a generally better way of testing your response than the usual 200 == transport.status.

Getting HTTP response headers

While you can obtain response headers from the XHR object using its getResponseHeader method, this makes for verbose code, and several implementations raise an exception when the header is not found. To make this easier, you can use the Ajax.Response#getHeader method, which delegates to the longer version and returns null if an exception occurs:

new Ajax.Request('/your/url', {
  onSuccess: function(response) {
    // Note how we brace against null values
    if ((response.getHeader('Server') || '').match(/Apache/))
      ++gApacheCount;
    // Remainder of the code
  }
});
Evaluating JSON headers

Some backends will return JSON not as response text, but in the X-JSON header. In this case, you don't even need to evaluate the returned JSON yourself, as Prototype automatically does so. It passes the result as the headerJSON property of the Ajax.Response object. Note that if there is no such header — or its contents are invalid — headerJSON will be set to null.

new Ajax.Request('/your/url', {
  onSuccess: function(transport) {
    transport.headerJSON
  }
});

Subclasses

Constructor

Instance methods

Ajax.Request.new

    • new Ajax.Request(url[, options])
    • url
      • String
    • The URL to fetch. When the same-origin policy is in effect (as it is in most cases), url must be a relative URL or an absolute URL that starts with a slash (i.e., it must not begin with http).

    • options
      • Object
    • Configuration for the request. See the Ajax for more information.

Creates a new Ajax.Request.

Ajax.Request#getHeader

    • Ajax.Request#getHeader(name)
    • name
      • String
    • The name of an HTTP header that may have been part of the response.

Returns the value of the given response header, or null if that header was not found.

Ajax.Request#success

    • Ajax.Request#success()
      • Boolean

Tests whether the request was successful.

Ajax.Responders

Description

A repository of global listeners notified about every step of Prototype-based Ajax requests.

Sometimes, you need to provide generic behaviors over all Ajax operations happening on the page (through Ajax.Request, Ajax.Updater or Ajax.PeriodicalUpdater).

For instance, you might want to automatically show an indicator when an Ajax request is ongoing, and hide it when none are. You may well want to factor out exception handling as well, logging those somewhere on the page in a custom fashion. The possibilities are myriad.

To achieve this, Prototype provides Ajax.Responders, which lets you register (and, if you wish, unregister later) responders, which are objects with specially-named methods. These names come from a set of general callbacks corresponding to different points in time (or outcomes) of an Ajax request's life cycle.

For instance, Prototype automatically registers a responder that maintains a nifty variable: Ajax.activeRequestCount. This represents, at a given time, the number of currently active Ajax requests — by monitoring their onCreate and onComplete events. The code for this is fairly simple:

Ajax.Responders.register({
  onCreate: function() {
    Ajax.activeRequestCount++;
  },
  onComplete: function() {
    Ajax.activeRequestCount--;
  }
});
Responder callbacks

The callbacks for responders are similar to the callbacks described in the Ajax, but take a different signature. They're invoked with three parameters: the requester object (i.e., the corresponding "instance" of Ajax.Request), the XMLHttpRequest object, and the result of evaluating the X-JSON response header, if any (can be null). They also execute in the context of the responder, bound to the this reference.

  • onCreate: Triggered whenever a requester object from the Ajax namespace is created, after its parameters are adjusted and before its XHR connection is opened. This takes two arguments: the requester object and the underlying XHR object.
  • onUninitialized (Not guaranteed): Invoked just after the XHR object is created.
  • onLoading (Not guaranteed): Triggered when the underlying XHR object is being setup, and its connection opened.
  • onLoaded (Not guaranteed): Triggered once the underlying XHR object is setup, the connection is open, and it is ready to send its actual request.
  • onInteractive (Not guaranteed): Triggered whenever the requester receives a part of the response (but not the final part), should it be sent in several packets.
  • onException: Triggered whenever an XHR error arises. Has a custom signature: the first argument is the requester (i.e. an Ajax.Request instance), and the second is the exception object.
  • onComplete: Triggered at the very end of a request's life-cycle, after the request completes, status-specific callbacks are called, and possible automatic behaviors are processed. Guaranteed to run regardless of what happened during the request.

Includes

Class methods

Ajax.Responders.register

    • Ajax.Responders.register(responder)
      • undefined
    • responder
      • Object
    • A list of functions with keys corresponding to the names of possible callbacks.

Add a group of responders to all Ajax requests.

Ajax.Responders.unregister

    • Ajax.Responders.unregister(responder)
      • undefined
    • responder
      • Object
    • A list of functions with keys corresponding to the names of possible callbacks.

Remove a previously-added group of responders.

As always, unregistering something requires you to use the very same object you used at registration. If you plan to use unregister, be sure to assign your responder to a variable before passing it into [[Ajax.Responders#register]] — don't pass it an object literal.

Ajax.Response

Description

A wrapper class around XmlHttpRequest for dealing with HTTP responses of Ajax requests.

An instance of Ajax.Response is passed as the first argument of all Ajax requests' callbacks. You will not need to create instances of Ajax.Response yourself.

Ajax.Response#getAllHeaders

    • Ajax.Response#getAllHeaders()

Returns a String containing all headers separated by line breaks. Does not throw errors if no headers are present the way its native counterpart does.

Ajax.Response#getAllResponseHeaders

    • Ajax.Response#getAllResponseHeaders()

Returns a String containing all headers separated by line breaks; throws an error if no headers exist. This is just a wrapper around the XmlHttpRequest method of the same name. Prefer it's shorter counterpart: Ajax.Response#getAllHeaders.

Ajax.Response#getHeader

    • Ajax.Response#getHeader(name)

See Ajax.Request#getHeader.

Ajax.Response#getResponseHeader

    • Ajax.Response#getResponseHeader(name)

Returns the value of the requested header if present; throws an error otherwise. This is just a wrapper around the XmlHttpRequest method of the same name. Prefer it's shorter counterpart: Ajax.Response#getHeader.

Ajax.Response#headerJSON

Auto-evaluated content of the X-JSON header if present; null otherwise. This is useful to transfer small amounts of data.

Ajax.Response#readyState

    • Ajax.Response#readyState

A Number corresponding to the request's current state.

0 : "Uninitialized"<br /> 1 : "Loading"<br /> 2 : "Loaded"<br /> 3 : "Interactive"<br /> 4 : "Complete"

Ajax.Response#request

The request object itself (an instance of Ajax.Request or Ajax.Updater).

Ajax.Response#responseJSON

The JSON body of the response if the Content-type of the request is set to application/json; null otherwise.

Ajax.Response#responseText

    • Ajax.Response#responseText

The text body of the response.

Ajax.Response#responseXML

The XML body of the response if the Content-type of the request is set to application/xml; null otherwise.

Ajax.Response#status

The HTTP status code sent by the server.

Ajax.Response#statusText

    • Ajax.Response#statusText

The HTTP status text sent by the server.

Ajax.Response#transport

    • Ajax.Response#transport
      • XmlHttpRequest

The native XmlHttpRequest object itself.

Ajax.Updater

Description

A class that performs an Ajax request and updates a container's contents with the contents of the response.

Ajax.Updater is a subclass of Ajax.Request built for a common use-case.

Example
new Ajax.Updater('items', '/items', {
  parameters: { text: $F('text') }
});

This example will make a request to the URL /items (with the given parameters); it will then replace the contents of the element with the ID of items with whatever response it receives.

Callbacks

Ajax.Updater supports all the callbacks listed in the Ajax. Note that the onComplete callback will be invoked after the element is updated.

Additional options

Ajax.Updater has some options of its own apart from the common options described in the Ajax:

  • evalScripts ([[Boolean]]; defaults to false): Whether <script> elements in the response text should be evaluated.
  • insertion (String): By default, Element.update is used, meaning the contents of the response will replace the entire contents of the container. You may instead insert the response text without disrupting existing contents. The insertion option takes one of four strings — top, bottom, before, or after — and inserts the contents of the response in the manner described by Element#insert.
More About evalScripts

If you use evalScripts: true, any inline <script> block will be evaluated. This does not mean it will be evaluated in the global scope; it won't, and that has important ramifications for your var and function statements. Also note that only inline <script> blocks are supported; external scripts are ignored. See String#evalScripts for the details.

Single container, or success/failure split?

The examples above all assume you're going to update the same container whether your request succeeds or fails. Instead, you may want to update only for successful requests, or update a different container on failed requests.

To achieve this, you can pass an object instead of a DOM element for the container parameter. This object must have a success property whose value identifies the container to be updated on successful requests.

If you also provide it with a failure property, its value will be used as the container for failed requests.

In the following code, only successful requests get an update:

new Ajax.Updater({ success: 'items' }, '/items', {
  parameters: { text: $F('text') },
  insertion: 'bottom'
});

This next example assumes failed requests will deliver an error message as response text — one that should be shown to the user in another area:

new Ajax.Updater({ success: 'items', failure: 'notice' }, '/items',
  parameters: { text: $F('text') },
  insertion: 'bottom'
});

Superclass

Constructor

Ajax.Updater.new

    • new Ajax.Updater(container, url[, options])
    • container
      • String
      • Element
    • The DOM element whose contents to update as a result of the Ajax request. Can be a DOM node or a string that identifies a node's ID.

    • url
      • String
    • The URL to fetch. When the same-origin policy is in effect (as it is in most cases), url must be a relative URL or an absolute URL that starts with a slash (i.e., it must not begin with http).

    • options
      • Object
    • Configuration for the request. See the Ajax for more information.

Creates a new Ajax.Updater.

Ajax.activeRequestCount

Represents the number of active XHR requests triggered through Ajax.Request, Ajax.Updater, or Ajax.PeriodicalUpdater.

DOM section

Description

Extensions to DOM elements, plus other utilities for DOM traversal and modification.

Prototype's DOM extensions represent a large portion of where you'll spend your time. Prototype adds many convenience methods to elements returned by the $ function. For instance, you can write

$('comments').addClassName('active').show();

to get the element with the ID of comments, add a class name to it, and show it (if it was previously hidden).

In other words, Prototype adds "instance" methods to DOM nodes. This is made possible by direct extension of the backing DOM objects (in browsers that support it) and by manual extension of individual nodes (in browsers that do not).

Namespaces

  • Abstract

  • document

    Prototype extends the built-in document object with several convenience methods related to events.

  • Form

    Utilities for dealing with forms in the DOM.

Classes

  • Element

  • Event

    The namespace for Prototype's event system.

  • Selector

    A class that queries the document for elements that match a given CSS selector.

Utilities

Abstract

Classes

Abstract.EventObserver

Abstract.TimedObserver

Description

An abstract DOM element observer class, subclasses of which can be used to periodically check a value and trigger a callback when the value has changed.

A TimedObserver object will try to check a value using the getValue() instance method which must be defined by the subclass. There are two out-of-the-box subclasses: Form.Observer, which serializes a form and triggers when the result has changed; and Form.Element.Observer, which triggers when the value of a given form field changes.

Using TimedObserver implementations is straightforward; simply instantiate them with appropriate arguments. For example:

new Form.Element.Observer(
  'myelement',
  0.2,  // 200 milliseconds
  function(el, value){
    alert('The form control has changed value to: ' + value)
  }
)

Now that we have instantiated an object, it will check the value of the form control every 0.2 seconds and alert us of any change. While it is useless to alert the user of his own input (like in the example), we could be doing something useful like updating a certain part of the UI or informing the application on server of stuff happening (over Ajax).

The callback function is always called with 2 arguments: the element given when the observer instance was made and the actual value that has changed and caused the callback to be triggered in the first place.

Creating Your Own TimedObserver Implementations

It's easy to create your own TimedObserver implementations: Simply subclass TimedObserver and provide the getValue() method. For example, this is the complete source code for Form.Element.Observer:

Form.Element.Observer = Class.create(Abstract.TimedObserver, {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Abstract.TimedObserver.new

    • new Abstract.TimedObserver(element, frequency, callback)
    • element
      • String
      • Element
    • The DOM element to watch. Can be an element instance or an ID.

    • frequency
      • Number
    • The frequency, in seconds — e.g., 0.33 to check for changes every third of a second.

    • callback
      • Function
    • The callback to trigger when the value changes.

Initializes an Abstract.TimedObserver; used by subclasses.

document

Description

Prototype extends the built-in document object with several convenience methods related to events.

Namespaces

  • document.viewport

    The document.viewport namespace contains methods that return information about the viewport — the rectangle that represents the portion of a web page within view. In other words, it's the browser window minus all chrome.

Class properties

Instance methods

document.viewport

Description

The document.viewport namespace contains methods that return information about the viewport — the rectangle that represents the portion of a web page within view. In other words, it's the browser window minus all chrome.

document.viewport.getDimensions

    • document.viewport.getDimensions()

Returns an object containing viewport dimensions in the form { width: Number, height: Number }.

The viewport is the subset of the browser window that a page occupies — the "usable" space in a browser window.

Example
document.viewport.getDimensions();
//-> { width: 776, height: 580 }

document.viewport.getHeight

    • document.viewport.getHeight()

Returns the height of the viewport.

Equivalent to document.viewport.getDimensions().height.

document.viewport.getScrollOffsets

    • document.viewport.getScrollOffsets()

Returns the viewport's horizontal and vertical scroll offsets.

Returns an array in the form of [leftValue, topValue]. Also accessible as properties: { left: leftValue, top: topValue }.

Examples
document.viewport.getScrollOffsets();
//-> { left: 0, top: 0 }

window.scrollTo(0, 120);
document.viewport.getScrollOffsets();
//-> { left: 0, top: 120 }

document.viewport.getWidth

    • document.viewport.getWidth()

Returns the width of the viewport.

Equivalent to calling document.viewport.getDimensions().width.

document.fire

    • document.fire(eventName[, memo][, bubble = true])
    • memo
      • Metadata for the event. Will be accessible through the event's memo property.

      • bubble
        • Boolean
      • Whether the event will bubble.

    Fires a custom event of name eventName with document as the target.

    document.fire is the document-wide version of Element.fire.

    Custom events must include a colon (:) in their names.

    document.observe

      • document.observe(eventName, handler)

    Listens for the given event over the entire document. Can also be used for listening to "dom:loaded" event.

    document.observe is the document-wide version of Element#observe. Using document.observe is equivalent to Event.observe(document, eventName, handler).

    The "dom:loaded" event

    One really useful event generated by Prototype that you might want to observe on the document is "dom:loaded". On supporting browsers it fires on DOMContentLoaded and on unsupporting browsers it simulates it using smart workarounds. If you used window.onload before you might want to switch to dom:loaded because it will fire immediately after the HTML document is fully loaded, but before images on the page are fully loaded. The load event on window only fires after all page images are loaded, making it unsuitable for some initialization purposes like hiding page elements (so they can be shown later).

    Example
    document.observe("dom:loaded", function() {
      // initially hide all containers for tab content
      $$('div.tabcontent').invoke('hide');
    });

    document.on

      • document.on(element, eventName[, selector], callback)

    See Event.on.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    document.stopObserving

      • document.stopObserving([eventName][, handler])

    Unregisters an event handler from the document.

    document.stopObserving is the document-wide version of Element.stopObserving.

    document.loaded

      • document.loaded
        • Boolean

    Whether the full DOM tree is ready for manipulation.

    document#on

      • document#on(eventName[, selector], callback)

    See Event.on.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element

    Classes

    • Element.Layout

      A set of key/value pairs representing measurements of various dimensions of an element.

    • Element.Offset

      A representation of the top- and left-offsets of an element relative to another.

    Mixins

    Constructor

    Element.new

      • new Element(tagName[, attributes])
      • tagName
        • String
      • The name of the HTML element to create.

      • attributes
        • Object
      • An optional group of attribute/value pairs to set on the element.

    Creates an HTML element with tagName as the tag name, optionally with the given attributes. This can be markedly more concise than working directly with the DOM methods, and takes advantage of Prototype's workarounds for various browser issues with certain attributes:

    Example
    // The old way:
    var a = document.createElement('a');
    a.setAttribute('class', 'foo');
    a.setAttribute('href', '/foo.html');
    a.appendChild(document.createTextNode("Next page"));
    
    // The new way:
    var a = new Element('a', { 'class': 'foo', href: '/foo.html' }).update("Next page");

    Element.Layout

    Description

    A set of key/value pairs representing measurements of various dimensions of an element.

    <h4>Overview</h4>

    The Element.Layout class is a specialized way to measure elements. It helps mitigate:

    • The convoluted steps often needed to get common measurements for elements.
    • The tendency of browsers to report measurements in non-pixel units.
    • The quirks that lead some browsers to report inaccurate measurements.
    • The difficulty of measuring elements that are hidden.

    <h4>Usage</h4>

    Instantiate an Element.Layout class by passing an element into the constructor:

    var layout = new Element.Layout(someElement);
    

    You can also use Element.getLayout, if you prefer.

    Once you have a layout object, retrieve properties using Hash's familiar get and set syntax.

    layout.get('width');  //-> 400
    layout.get('top');    //-> 180
    

    The following are the CSS-related properties that can be retrieved. Nearly all of them map directly to their property names in CSS. (The only exception is for borders — e.g., border-width instead of border-left-width.)

    • height
    • width
    • top
    • left
    • right
    • bottom
    • border-left
    • border-right
    • border-top
    • border-bottom
    • padding-left
    • padding-right
    • padding-top
    • padding-bottom
    • margin-top
    • margin-bottom
    • margin-left
    • margin-right

    In addition, these "composite" properties can be retrieved:

    • padding-box-width (width of the content area, from the beginning of the left padding to the end of the right padding)
    • padding-box-height (height of the content area, from the beginning of the top padding to the end of the bottom padding)
    • border-box-width (width of the content area, from the outer edge of the left border to the outer edge of the right border)
    • border-box-height (height of the content area, from the outer edge of the top border to the outer edge of the bottom border)
    • margin-box-width (width of the content area, from the beginning of the left margin to the end of the right margin)
    • margin-box-height (height of the content area, from the beginning of the top margin to the end of the bottom margin)

    <h4>Caching</h4>

    Because these properties can be costly to retrieve, Element.Layout behaves differently from an ordinary Hash.

    First: by default, values are "lazy-loaded" — they aren't computed until they're retrieved. To measure all properties at once, pass a second argument into the constructor:

    var layout = new Element.Layout(someElement, true);
    

    Second: once a particular value is computed, it's cached. Asking for the same property again will return the original value without re-computation. This means that an instance of Element.Layout becomes stale when the element's dimensions change. When this happens, obtain a new instance.

    <h4>Hidden elements</h4>

    Because it's a common case to want the dimensions of a hidden element (e.g., for animations), it's possible to measure elements that are hidden with display: none.

    However, it's only possible to measure a hidden element if its parent is visible. If its parent (or any other ancestor) is hidden, any width and height measurements will return 0, as will measurements for top|bottom|left|right.

    Superclass

    Instance methods

    Element.Layout.new

      • new Element.Layout(element[, preCompute = false])
      • element
        • Element
      • The element to be measured.

      • preCompute
        • Boolean
      • Whether to compute all values at once. Default is false.

    Declare a new layout hash.

    The preCompute argument determines whether measurements will be lazy-loaded or not. If you plan to use many different measurements, it's often more performant to pre-compute, as it minimizes the amount of overhead needed to measure. If you need only one or two measurements, it's probably not worth it.

    Element.Layout#get

      • Element.Layout#get(property)

    Retrieve the measurement specified by property. Will throw an error if the property is invalid.

    Caveats
    • Element.Layout can measure the dimensions of an element hidden with CSS (display: none), but only if its parent element is visible.

    Element.Layout#toCSS

      • Element.Layout#toCSS([keys...])
      • keys
        • String
      • A space-separated list of keys to include.

    Converts the layout hash to a plain object of CSS property/value pairs, optionally including only the given keys.

    Keys can be passed into this method as individual arguments or separated by spaces within a string.

    // Equivalent statements:
    someLayout.toCSS('top', 'bottom', 'left', 'right');
    someLayout.toCSS('top bottom left right');
    

    Useful for passing layout properties to Element.setStyle.

    Element.Layout#toHash

      • Element.Layout#toHash([keys...])
      • keys
        • String
      • A space-separated list of keys to include.

    Converts the layout hash to an ordinary hash of key/value pairs, optionally including only the given keys.

    Keys can be passed into this method as individual arguments or separated by spaces within a string.

    // Equivalent statements:
    someLayout.toHash('top', 'bottom', 'left', 'right');
    someLayout.toHash('top bottom left right');

    Element.Layout#toObject

      • Element.Layout#toObject([keys...])
      • keys
        • String
      • A space-separated list of keys to include.

    Converts the layout hash to a plain object of key/value pairs, optionally including only the given keys.

    Keys can be passed into this method as individual arguments or separated by spaces within a string.

    // Equivalent statements:
    someLayout.toObject('top', 'bottom', 'left', 'right');
    someLayout.toObject('top bottom left right');

    Element.Layout.COMPOSITE_PROPERTIES

      • Element.Layout.COMPOSITE_PROPERTIES

    A list of all composite properties. Composite properties don't map directly to CSS properties — they're combinations of other properties.

    Element.Layout.PROPERTIES

      • Element.Layout.PROPERTIES

    A list of all measurable properties.

    Element.Methods

    Description

    Element.Methods is a mixin for DOM elements. The methods of this object are accessed through the $ utility or through the Element object and shouldn't be accessed directly.

    Examples

    Hide the element

    $(element).hide(); 
    

    Return an Enumerable of all descendant nodes of the element with the id "article"

    $('articles').descendants();

    Element.Offset

    Description

    A representation of the top- and left-offsets of an element relative to another.

    All methods that compute offsets return an instance of Element.Offset.

    Element.Offset.new

      • new Element.Offset(left, top)

    Instantiates an Element.Offset. You shouldn't need to call this directly.

    Element.Offset#inspect

      • Element.Offset#inspect()

    Returns a debug-friendly representation of the offset.

    Element.Offset#relativeTo

      • Element.Offset#relativeTo(offset)
      • offset
        • Element.Offset
      • Another offset to compare to.

    Returns a new Element.Offset with its origin at the given offset. Useful for determining an element's distance from another arbitrary element.

    Element.Offset#toArray

      • Element.Offset#toArray()

    Returns an array representation fo the offset in [x, y] format.

    Element.Offset#toString

      • Element.Offset#toString()

    Element.absolutize

    Turns element into an absolutely-positioned element without changing its position in the page layout.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.addClassName

      • Element.addClassName(element, className)
      • className
        • String
      • The class name to add.

    Adds the given CSS class to element.

    Example

    Assuming this HTML:

    language: html
    <div id="mutsu" class="apple fruit"></div>
    

    Then:

    $('mutsu').className;
    // -> 'apple fruit'
    $('mutsu').addClassName('food');
    $('mutsu').className;
    // -> 'apple fruit food'

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.addMethods

      • Element.addMethods
      • Element.addMethods(tagName, methods)
        • undefined
      • tagName
        • String
      • (Optional) The name of the HTML tag for which the methods should be available; if not given, all HTML elements will have the new methods.

      • methods
        • Object
      • A hash of methods to add.

    Element.addMethods makes it possible to mix your own methods into the Element object and extended element instances (all of them, or only ones with the given HTML tag if you specify tagName).

    You define the methods in a hash that you provide to Element.addMethods. Here's an example adding two methods:

    Element.addMethods({
    
      // myOwnMethod: Do something cool with the element
      myOwnMethod: function(element) {
        if (!(element = $(element))) return;
        // ...do smething with 'element'...
        return element;
      },
    
      // wrap: Wrap the element in a new element using the given tag
      wrap: function(element, tagName) {
        var wrapper;
        if (!(element = $(element))) return;
        wrapper = new Element(tagName);
        element.parentNode.replaceChild(wrapper, element);
        wrapper.appendChild(element);
        return wrapper;
      }
    
    });
    

    Once added, those can be used either via Element:

    // Wrap the element with the ID 'foo' in a div
    Element.wrap('foo', 'div');
    

    ...or as instance methods of extended elements:

    // Wrap the element with the ID 'foo' in a div
    $('foo').wrap('div');
    

    Note the following requirements and conventions for methods added to Element:

    • The first argument is always an element or ID, by convention this argument is called element.
    • The method passes the element argument through $ and typically returns if the result is undefined.
    • Barring a good reason to return something else, the method returns the extended element to enable chaining.

    Our myOwnMethod method above returns the element because it doesn't have a good reason to return anything else. Our wrap method returns the wrapper, because that makes more sense for that method.

    Extending only specific elements

    If you call Element.addMethods with two arguments, it will apply the methods only to elements with the given HTML tag:

    Element.addMethods('DIV', my_div_methods);
    // the given methods are now available on DIV elements, but not others
    

    You can also pass an Array of tag names as the first argument:

    Element.addMethods(['DIV', 'SPAN'], my_additional_methods);
    // DIV and SPAN now both have the given methods
    

    (Tag names in the first argument are not case sensitive.)

    Note: Element.addMethods has built-in security which prevents you from overriding native element methods or properties (like getAttribute or innerHTML), but nothing prevents you from overriding one of Prototype's methods. Prototype uses a lot of its methods internally; overriding its methods is best avoided or at least done only with great care.

    Example 1

    Our wrap method earlier was a complete example. For instance, given this paragraph:

    language: html
    <p id="first">Some content...</p>
    

    ...we might wrap it in a div:

    $('first').wrap('div');
    

    ...or perhaps wrap it and apply some style to the div as well:

    $('first').wrap('div').setStyle({
      backgroundImage: 'url(images/rounded-corner-top-left.png) top left'
    });
    
    Example 2

    We can add a method to elements that makes it a bit easier to update them via Ajax.Updater:

    Element.addMethods({
      ajaxUpdate: function(element, url, options) {
        if (!(element = $(element))) return;
        element.update('<img src="/images/spinner.gif" alt="Loading...">');
        options = options || {};
        options.onFailure = options.onFailure || defaultFailureHandler.curry(element);
        new Ajax.Updater(element, url, options);
        return element;
      }
    });
    

    Now we can update an element via an Ajax call much more concisely than before:

    $('foo').ajaxUpdate('/new/content');
    

    That will use Ajax.Updater to load new content into the 'foo' element, showing a spinner while the call is in progress. It even applies a default failure handler (since we didn't supply one).

    Element.adjacent

      • Element.adjacent(element, selector...)
      • selector
        • String
      • A CSS selector.

    Finds all siblings of the current element that match the given selector(s). If you provide multiple selectors, siblings matching any of the selectors are included. If a sibling matches multiple selectors, it is only included once. The order of the returned array is not defined.

    Example

    Assuming this list:

    language: html
    <ul id="cities">
      <li class="us" id="nyc">New York</li>
      <li class="uk" id="lon">London</li>
      <li class="us" id="chi">Chicago</li>
      <li class="jp" id="tok">Tokyo</li>
      <li class="us" id="la">Los Angeles</li>
      <li class="us" id="aus">Austin</li>
    </ul>
    

    Then:

    $('nyc').adjacent('li.us');
    // -> [li#chi, li#la, li#aus]
    $('nyc').adjacent('li.uk', 'li.jp');
    // -> [li#lon, li#tok]

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.ancestors

      • Element.ancestors(element)

    Collects all of element's ancestor elements and returns them as an array of extended elements.

    The returned array's first element is element's direct ancestor (its parentNode), the second one is its grandparent, and so on until the <html> element is reached. <html> will always be the last member of the array. Calling ancestors on the <html> element will return an empty array.

    Example

    Assuming:

    language: html
    <html>
    [...]
      <body>
        <div id="father">
          <div id="kid">
          </div>
        </div>
      </body>
    </html>
    

    Then:

    $('kid').ancestors();
    // -> [div#father, body, html]

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.childElements

      • Element.childElements(element)

    Collects all of the element's children and returns them as an array of [[Element.extended extended]] elements, in document order. The first entry in the array is the topmost child of element, the next is the child after that, etc.

    Like all of Prototype's DOM traversal methods, Element.childElements ignores text nodes and returns element nodes only.

    Example

    Assuming:

    language: html
    <div id="australopithecus">
      Some text in a text node
      <div id="homo-erectus">
        <div id="homo-neanderthalensis"></div>
        <div id="homo-sapiens"></div>
      </div>
    </div>
    

    Then:

    $('australopithecus').childElements();
    // -> [div#homo-erectus]
    
    $('homo-erectus').childElements();
    // -> [div#homo-neanderthalensis, div#homo-sapiens]
    
    $('homo-sapiens').childElements();
    // -> []

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.classNames

    Deprecated
      • Element.classNames(element)

    Returns a new instance of [[Element.ClassNames]], an Enumerable object used to read and write CSS class names of element.

    Deprecated, please see Element.addClassName, Element.removeClassName, and Element.hasClassName. If you want an array of classnames, you can use $w(element.className).

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.cleanWhitespace

      • Element.cleanWhitespace(element)

    Removes all of element's child text nodes that contain only whitespace. Returns element.

    This can be very useful when using standard properties like nextSibling, previousSibling, firstChild or lastChild to walk the DOM. Usually you'd only do that if you are interested in all of the DOM nodes, not just Elements (since if you just need to traverse the Elements in the DOM tree, you can use Element.up, Element.down, Element.next, and Element.previous instead).

    Example

    Consider the following HTML snippet:

    language: html
    <ul id="apples">
      <li>Mutsu</li>
      <li>McIntosh</li>
      <li>Ida Red</li>
    </ul>
    

    Let's grab what we think is the first list item using the raw DOM method:

    var element = $('apples');
    element.firstChild.innerHTML;
    // -> undefined
    

    It's undefined because the firstChild of the apples element is a text node containing the whitespace after the end of the ul and before the first li.

    If we remove the useless whitespace, then firstChild works as expected:

    var element = $('apples');
    element.cleanWhitespace();
    element.firstChild.innerHTML;
    // -> 'Mutsu'

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.clone

      • Element.clone(element, deep)
      • deep
        • Boolean
      • Whether to clone element's descendants as well.

    Returns a duplicate of element.

    A wrapper around DOM Level 2 Node#cloneNode, Element.clone cleans up any expando properties defined by Prototype.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.clonePosition

      • Element.clonePosition(element, source[, options])
      • source
        • Element
        • String
      • The source element (or its ID).

      • options
        • Object
      • The position fields to clone.

    Clones the position and/or dimensions of source onto the element as defined by options, with an optional offset for the left and top properties.

    Note that the element will be positioned exactly like source whether or not it is part of the same CSS containing block.

    Options

    <table class='options'> <thead> <tr> <th style='text-align: left; padding-right: 1em'>Name</th> <th style='text-align: left; padding-right: 1em'>Default</th> <th style='text-align: left; padding-right: 1em'>Description</th> </tr> </thead> <tbody> <tr> <td><code>setLeft</code></td> <td><code>true</code></td> <td>Clones <code>source</code>'s <code>left</code> CSS property onto <code>element</code>.</td> </tr> <tr> <td><code>setTop</code></td> <td><code>true</code></td> <td>Clones <code>source</code>'s <code>top</code> CSS property onto <code>element</code>.</td> </tr> <tr> <td><code>setWidth</code></td> <td><code>true</code></td> <td>Clones <code>source</code>'s <code>width</code> onto <code>element</code>.</td> </tr> <tr> <td><code>setHeight</code></td> <td><code>true</code></td> <td>Clones <code>source</code>'s <code>width</code> onto <code>element</code>.</td> </tr> <tr> <td><code>offsetLeft</code></td> <td><code>0</code></td> <td>Number by which to offset <code>element</code>'s <code>left</code> CSS property.</td> </tr> <tr> <td><code>offsetTop</code></td> <td><code>0</code></td> <td>Number by which to offset <code>element</code>'s <code>top</code> CSS property.</td> </tr> </tbody> </table>

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.cumulativeOffset

      • Element.cumulativeOffset(element)

    Returns the offsets of element from the top left corner of the document.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.cumulativeScrollOffset

      • Element.cumulativeScrollOffset(element)

    Calculates the cumulative scroll offset of an element in nested scrolling containers.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.descendantOf

      • Element.descendantOf(element, ancestor)
        • Boolean
      • ancestor
        • Element
        • String
      • The element to check against (or its ID).

    Checks if element is a descendant of ancestor.

    Example

    Assuming:

    language: html
    <div id="australopithecus">
      <div id="homo-erectus">
        <div id="homo-sapiens"></div>
      </div>
    </div>
    

    Then:

    $('homo-sapiens').descendantOf('australopithecus');
    // -> true
    
    $('homo-erectus').descendantOf('homo-sapiens');
    // -> false

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.descendants

      • Element.descendants(element)

    Collects all of the element's descendants (its children, their children, etc.) and returns them as an array of extended elements. As with all of Prototype's DOM traversal methods, only Elements are returned, other nodes (text nodes, etc.) are skipped.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.down

      • Element.down
      • Element.down(element[, index = 0])
      • expression
        • String
      • A CSS selector.

    Returns element's first descendant (or the Nth descendant, if index is specified) that matches expression. If no expression is provided, all descendants are considered. If no descendant matches these criteria, undefined is returned.

    More information

    The Element.down method is part of Prototype's ultimate DOM traversal toolkit (check out Element.up, Element.next and Element.previous for some more Prototypish niceness). It allows precise index-based and/or CSS rule-based selection of any of the element's descendants.

    As it totally ignores text nodes (it only returns elements), you don't have to worry about whitespace nodes.

    And as an added bonus, all elements returned are already extended (see Element.extend) allowing chaining:

    $(element).down(1).next('li', 2).hide();
    

    Walking the DOM has never been that easy!

    Arguments

    If no arguments are passed, element's first descendant is returned (this is similar to calling firstChild except Element.down returns an extended element.

    If index is defined, element's corresponding descendant is returned. (This is equivalent to selecting an element from the array of elements returned by the method Element.descendants.) Note that the first element has an index of 0.

    If expression is defined, Element.down will return the first descendant that matches it. This is a great way to grab the first item in a list for example (just pass in 'li' as the method's first argument).

    If both expression and index are defined, Element.down will collect all the descendants matching the given CSS expression and will return the one at the specified index.

    In all of the above cases, if no descendant is found, undefined will be returned.

    Examples
    language: html
    <ul id="fruits">
      <li id="apples">
        <ul>
          <li id="golden-delicious">Golden Delicious</li>
          <li id="mutsu" class="yummy">Mutsu</li>
          <li id="mcintosh" class="yummy">McIntosh</li>
          <li id="ida-red">Ida Red</li>
        </ul>
      </li>
    </ul>
    

    Get the first descendant of "#fruites":

    $('fruits').down();
    // or:
    $('fruits').down(0);
    // -> li#apples
    

    Get the third descendant of "#fruits":

    $('fruits').down(3);
    // -> li#golden-delicious
    

    Get the first descendant of "#apples" with the node name "li":

    $('apples').down('li');
    // -> li#golden-delicious
    

    Get the first descendant of "#apples" with the node name "li" and the class name "yummy":

    $('apples').down('li.yummy');
    // -> li#mutsu
    

    Get the second descendant of "#fruits" with the class name "yummy":

    $('fruits').down('.yummy', 1);
    // -> li#mcintosh
    

    Try to get the ninety-ninth descendant of "#fruits":

    $('fruits').down(99);
    // -> undefined

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.empty

    Tests whether element is empty (i.e., contains only whitespace).

    Examples
    <div id="wallet">     </div>
    <div id="cart">full!</div>
    
    $('wallet').empty();
    // -> true
    
    $('cart').empty();
    // -> false

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.extend

    Extends the given element instance with all of the Prototype goodness and syntactic sugar, as well as any extensions added via Element.addMethods. (If the element instance was already extended, this is a no-op.)

    You only need to use Element.extend on element instances you've acquired directly from the DOM; all Prototype methods that return element instances (such as $, Element.down, etc.) will pre-extend the element before returning it.

    Check out "How Prototype extends the DOM" for more about element extensions.

    Details

    Specifically, Element.extend extends the given instance with the methods contained in Element.Methods and Element.Methods.Simulated. If element is an input, textarea, or select element, it will also be extended with the methods from Form.Element.Methods. If it is a form element, it will also be extended with the methods from Form.Methods.

    Element.fire

      • Element.fire(element, eventName[, memo][, bubble = true])

    See Event.fire.

    Fires a custom event with the current element as its target.

    Element.fire creates a custom event with the given name, then triggers it on the given element. The custom event has all the same properties and methods of native events. Like a native event, it will bubble up through the DOM unless its propagation is explicitly stopped.

    The optional second argument will be assigned to the memo property of the event object so that it can be read by event handlers.

    Custom events are dispatched synchronously: Element.fire waits until the event finishes its life cycle, then returns the event itself.

    Note

    Element.fire does not support firing native events. All custom event names must be namespaced (using a colon). This is to avoid custom event names conflicting with non-standard native DOM events such as mousewheel and DOMMouseScroll.

    Examples
    document.observe("widget:frobbed", function(event) {
      console.log("Element with ID (" + event.target.id +
       ") frobbed widget #" + event.memo.widgetNumber + ".");
    });
    
    var someNode = $('foo');
    someNode.fire("widget:frobbed", { widgetNumber: 19 });
    
    //-> "Element with ID (foo) frobbed widget #19."
    
    Tip

    Events that have been stopped with Event.stop will have a boolean stopped property set to true. Since Element.fire returns the custom event, you can inspect this property to determine whether the event was stopped.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.firstDescendant

      • Element.firstDescendant(element)

    Returns the first child that is an element.

    This is opposed to the firstChild DOM property, which will return any node, including text nodes and comment nodes.

    Examples
    language: html
    <div id="australopithecus">
      <div id="homo-erectus"><!-- Latin is super -->
        <div id="homo-neanderthalensis"></div>
        <div id="homo-sapiens"></div>
      </div>
    </div>
    

    Then:

    $('australopithecus').firstDescendant();
    // -> div#homo-erectus
    
    // the DOM property returns any first node
    $('homo-erectus').firstChild;
    // -> comment node "Latin is super"
    
    // this is what we want!
    $('homo-erectus').firstDescendant();
    // -> div#homo-neanderthalensis

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.getDimensions

      • Element.getDimensions(element)

    Finds the computed width and height of element and returns them as key/value pairs of an object.

    For backwards-compatibility, these dimensions represent the dimensions of the element's "border box" (including CSS padding and border). This is equivalent to the built-in offsetWidth and offsetHeight browser properties.

    Note that all values are returned as numbers only although they are expressed in pixels.

    Caveats
    • If the element is hidden via display: none in CSS, this method will attempt to measure the element by temporarily removing that CSS and applying visibility: hidden and position: absolute. This gives the element dimensions without making it visible or affecting the positioning of surrounding elements — but may not give accurate results in some cases. Element.measure is designed to give more accurate results.

    • In order to avoid calling the method twice, you should consider caching the returned values in a variable, as shown in the example below.

    • For more complex use cases, use Element.measure, which is able to measure many different aspects of an element's dimensions and offsets.

    Examples
    language: html
    <div id="rectangle" style="font-size: 10px; width: 20em; height: 10em"></div>
    

    Then:

    var dimensions = $('rectangle').getDimensions();
    // -> {width: 200, height: 100}
    
    dimensions.width;
    // -> 200
    
    dimensions.height;
    // -> 100

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.getElementsBySelector

      • Element.getElementsBySelector(element, selector)

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.getHeight

      • Element.getHeight(element)

    Returns the height of element.

    This method returns correct values on elements whose display is set to none either in an inline style rule or in an CSS stylesheet.

    For performance reasons, if you need to query both width and height of element, you should consider using Element.getDimensions instead.

    Note that the value returned is a number only although it is expressed in pixels.

    Examples
    language: html
    <div id="rectangle" style="font-size: 10px; width: 20em; height: 10em"></div>
    

    Then:

    $('rectangle').getHeight();
    // -> 100

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.getLayout

      • Element.getLayout(element[, preCompute = false])
      • element
        • Element
      • The element to be measured.

      • preCompute
        • Boolean
      • Whether to compute all values at once. Default is false.

    Returns an instance of Element.Layout for measuring an element's dimensions.

    Note that this method returns a new Element.Layout object each time it's called. If you want to take advantage of measurement caching, retain a reference to one Element.Layout object, rather than calling Element.getLayout whenever you need a measurement. You should call Element.getLayout again only when the values in an existing Element.Layout object have become outdated.

    If the preCompute argument is true, all properties will be measured when the layout object is instantiated. If you plan to measure several properties of an element's dimensions, it's probably worth it to get a pre-computed hash.

    Examples
    var layout = $('troz').getLayout();
    
    layout.get('width');  //-> 150
    layout.get('height'); //-> 500
    layout.get('padding-left');  //-> 10
    layout.get('margin-left');   //-> 25
    layout.get('border-top');    //-> 5
    layout.get('border-bottom'); //-> 5
    
    // Won't re-compute width; remembers value from first time.
    layout.get('width');  //-> 150
    
    // Composite values obtained by adding together other properties;
    // will re-use any values we've already looked up above.
    layout.get('padding-box-width'); //-> 170
    layout.get('border-box-height'); //-> 510
    
    Caveats
    • Instances of Element.Layout can measure the dimensions of an element hidden with CSS (display: none), but only if its parent element is visible.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.getOffsetParent

      • Element.getOffsetParent(element)

    Returns element's closest positioned ancestor. If none is found, the body element is returned.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.getOpacity

      • Element.getOpacity(element)

    Returns the opacity of the element.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.getStorage

      • Element.getStorage(element)

    Returns the Hash object that stores custom metadata for this element.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.getStyle

      • Element.getStyle(element, style)
      • style
        • String
      • The property name to be retrieved.

    Returns the given CSS property value of element. The property can be specified in either its CSS form (font-size) or its camelized form (fontSize).

    This method looks up the CSS property of an element whether it was applied inline or in a stylesheet. It works around browser inconsistencies regarding float, opacity, which returns a value between 0 (fully transparent) and 1 (fully opaque), position properties (left, top, right and bottom) and when getting the dimensions (width or height) of hidden elements.

    Examples
    $(element).getStyle('font-size');
    // equivalent:
    
    $(element).getStyle('fontSize');
    // -> '12px'
    
    Notes

    Not all CSS shorthand properties are supported. You may only use the CSS properties described in the Document Object Model (DOM) Level 2 Style Specification.

    Old versions of Internet Explorer return literal values; other browsers return computed values.

    Consider the following HTML snippet:

    language: html
    <style>
      #test {
        font-size: 12px;
        margin-left: 1em;
      }
    </style>
    <div id="test"></div>
    

    Then:

    $('test').getStyle('margin-left');
    // -> '1em' in Internet Explorer,
    // -> '12px' elsewhere.
    

    Safari returns null for any non-inline property if the element is hidden (has display set to 'none').

    Caveats

    Early versions of Prototype attempted to "fix" this behavior for certain properties. A few examples:

    1. Reading and writing the CSS opacity property works exactly like calling Element.getOpacity and Element.setOpacity respectively. This lets us pretend that IE didn't have a properietary way to set opacity in versions 6-7.
    2. Browsers disagree on how to report certain properties of hidden elements (i.e., display: none). Opera, for instance, says that a hidden element has a width of 0px. It's an arguable point, but we return null in those cases instead (so as to agree with the majority behavior). In short: if an element is hidden, getStyle('width') and getStyle('height') will return null.
    3. In older versions of Internet Explorer, Prototype will return a pixel value for width and height, even if the literal value is a different unit. It does this by treating width like offsetWidth and height like offsetHeight. This is often the incorrect measurement, but it's a mistake we're stuck with for backward-compatibility. If you're trying to measure an element's dimensions, don't use getStyle; use Element.measure instead.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.getWidth

      • Element.getWidth(element)

    Returns the width of element.

    This method returns correct values on elements whose display is set to none either in an inline style rule or in an CSS stylesheet.

    For performance reasons, if you need to query both width and height of element, you should consider using Element.getDimensions instead.

    Note that the value returned is a number only although it is expressed in pixels.

    Examples
    language: html
    <div id="rectangle" style="font-size: 10px; width: 20em; height: 10em"></div>
    

    Then:

    $('rectangle').getWidth();
    // -> 200

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.hasClassName

      • Element.hasClassName(element, className)
        • Boolean

    Checks for the presence of CSS class className on element.

    Examples
    language: html
    <div id="mutsu" class="apple fruit food"></div>
    

    Then:

    $('mutsu').hasClassName('fruit');
    // -> true
    
    $('mutsu').hasClassName('vegetable');
    // -> false

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.hide

    Sets display: none on element. Returns element.

    Examples

    Hide a single element:

    <div id="error-message"></div>
    
    $('error-message').hide();
    // -> Element (and hides div#error-message)
    

    Hide multiple elements using Enumerable#each:

    ['content', 'navigation', 'footer'].each(Element.hide);
    // -> ['content', 'navigation', 'footer'] 
    

    Hide multiple elements using Enumerable#invoke:

    $('content', 'navigation', 'footer').invoke('hide');
    // -> [Element, Element, Element]

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.identify

      • Element.identify(element)

    Returns element's ID. If element does not have an ID, one is generated, assigned to element, and returned.

    Examples

    Original HTML:

      <ul>
        <li id="apple">apple</li>
        <li>orange</li>
      </ul>
    

    JavaScript:

      $('apple').identify();
      // -> 'apple'
    
      $('apple').next().identify();
      // -> 'anonymous_element_1'
    

    Resulting HTML:

      <ul>
        <li id="apple">apple</li>
        <li id="anonymous_element_1">orange</li>
      </ul>

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.immediateDescendants

    Deprecated
      • Element.immediateDescendants(element)

    This method is deprecated, please see Element.childElements.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.insert

      • Element.insert(element, content)
      • content
        • String
        • Element
        • Object
      • The content to insert.

    Inserts content above, below, at the top, and/or at the bottom of the given element, depending on the option(s) given.

    insert accepts content in any of these forms:

    • String: A string of HTML to be parsed and rendered
    • Element: An Element instance to insert
    • ...any object with a toElement method: The method is called and the resulting element used
    • ...any object with a toHTML method: The method is called and the resulting HTML string is parsed and rendered

    The content argument can be the content to insert, in which case the implied insertion point is bottom, or an object that specifies one or more insertion points (e.g., { bottom: "foo", top: "bar" }).

    Accepted insertion points are:

    • before (as element's previous sibling)
    • after (as element's next sibling)
    • top (as element's first child)
    • bottom (as element's last child)

    Note that if the inserted HTML contains any <script> tag, these will be automatically evaluated after the insertion (insert internally calls [[String.evalScripts]] when inserting HTML).

    <h5>Examples</h5>

    Insert the given HTML at the bottom of the element (using the default):

    $('myelement').insert("<p>HTML to append</p>");
    
    $('myelement').insert({
      top: new Element('img', {src: 'logo.png'})
    });
    

    Put hrs before and after the element:

    $('myelement').insert({
      before: "<hr>",
      after: "<hr>"
    });

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.inspect

      • Element.inspect(element)

    Returns the debug-oriented string representation of element.

    For more information on inspect methods, see Object.inspect.

    language: html
    <ul>
      <li id="golden-delicious">Golden Delicious</li>
      <li id="mutsu" class="yummy apple">Mutsu</li>
      <li id="mcintosh" class="yummy">McIntosh</li>
      <li></li>
    </ul>
    

    And the associated JavaScript:

    $('golden-delicious').inspect();
    // -> '<li id="golden-delicious">'
    
    $('mutsu').inspect();
    // -> '<li id="mutsu" class="yummy apple">'
    
    $('mutsu').next().inspect();
    // -> '<li>'

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.makeClipping

      • Element.makeClipping(element)

    Simulates the poorly-supported CSS clip property by setting element's overflow value to hidden.

    To undo clipping, use Element.undoClipping.

    The visible area is determined by element's width and height.

    Example
    language:html
    <div id="framer">
      <img src="/assets/2007/1/14/chairs.jpg" alt="example" />
    </div>
    

    Then:

    $('framer').makeClipping().setStyle({width: '100px', height: '100px'});
    // -> Element
    

    Another example:

    language: html
    <a id="clipper" href="#">Click me to try it out.</a>
    
    <div id="framer">
      <img src="/assets/2007/2/24/chairs.jpg" alt="example" />
    </div>
    
    <script type="text/javascript" charset="utf-8">
      var Example = {
        clip: function(){
          $('clipper').update('undo clipping!');
          $('framer').makeClipping().setStyle({width: '100px', height: '100px'});
        },
        unClip: function(){
          $('clipper').update('clip!');
          $('framer').undoClipping();
        },
        toggleClip: function(event){
          if($('clipper').innerHTML == 'undo clipping!') Example.unClip();
          else Example.clip();
          Event.stop(event);
        }
      };
      Event.observe('clipper', 'click', Example.toggleClip);
    </script>

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.makePositioned

      • Element.makePositioned(element)

    Allows for the easy creation of a CSS containing block by setting element's CSS position to relative if its initial position is either static or undefined.

    To revert back to element's original CSS position, use Element.undoPositioned.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.match

      • Element.match(element, selector)
        • boolean
      • selector
        • String
      • A CSS selector.

    Checks if element matches the given CSS selector.

    Examples
    language: html
    <ul id="fruits">
      <li id="apples">
        <ul>
          <li id="golden-delicious">Golden Delicious</li>
          <li id="mutsu" class="yummy">Mutsu</li>
          <li id="mcintosh" class="yummy">McIntosh</li>
          <li id="ida-red">Ida Red</li>
        </ul>
      </li>
    </ul>
    

    Then:

    $('fruits').match('ul');
    // -> true
    
    $('mcintosh').match('li#mcintosh.yummy');
    // -> true
    
    $('fruits').match('p');
    // -> false

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.measure

      • Element.measure(element, property)

    Gives the pixel value of element's dimension specified by property.

    Useful for one-off measurements of elements. If you find yourself calling this method frequently over short spans of code, you might want to call Element.getLayout and operate on the Element.Layout object itself (thereby taking advantage of measurement caching).

    Examples
    $('troz').measure('width'); //-> 150
    $('troz').measure('border-top'); //-> 5
    $('troz').measure('top'); //-> 226
    
    Caveats
    • Element.measure can measure the dimensions of an element hidden with CSS (display: none), but only if its parent element is visible.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.next

      • Element.next
      • Element.next(element[, index = 0])
      • expression
        • String
      • A CSS selector.

    Returns element's first following sibling (or the Nth, if index is specified) that matches expression. If no expression is provided, all following siblings are considered. If none matches these criteria, undefined is returned.

    More information

    The Element.next method is part of Prototype's ultimate DOM traversal toolkit (check out Element.up, Element.down and Element.previous for some more Prototypish niceness). It allows precise index-based and/or CSS expression-based selection of any of element's following siblings. (Note that two elements are considered siblings if they have the same parent, so for example, the head and body elements are siblings—their parent is the html element.)

    As it totally ignores text nodes (it only returns elements), you don't have to worry about whitespace nodes.

    And as an added bonus, all elements returned are already extended (see Element.extend) allowing chaining:

    $(element).down(1).next('li', 2).hide();
    

    Walking the DOM has never been that easy!

    Arguments

    If no arguments are passed, element's following sibling is returned (this is similar as calling nextSibling except Element.next returns an already extended element).

    If index is defined, element's corresponding following sibling is returned. (This is equivalent to selecting an element from the array of elements returned by the method Element.nextSiblings). Note that the sibling right below element has an index of 0.

    If expression is defined, Element.next will return the element first following sibling that matches it.

    If both expression and index are defined, Element.next will collect all of element's following siblings matching the given CSS expression and will return the one at the specified index.

    In all of the above cases, if no following sibling is found, undefined will be returned.

    Examples
    language: html
    <ul id="fruits">
      <li id="apples">
        <h3 id="title">Apples</h3>
        <ul id="list-of-apples">
          <li id="golden-delicious">Golden Delicious</li>
          <li id="mutsu">Mutsu</li>
          <li id="mcintosh" class="yummy">McIntosh</li>
          <li id="ida-red" class="yummy">Ida Red</li>
        </ul>
        <p id="saying">An apple a day keeps the doctor away.</p>  
      </li>
    </ul>
    

    Get the first sibling after "#title":

    $('title').next();
    // or:
    $('title').next(0);
    // -> ul#list-of-apples
    

    Get the second sibling after "#title":

    $('title').next(1);
    // -> p#saying
    

    Get the first sibling after "#title" with node name "p":

    $('title').next('p');
    // -> p#sayings
    

    Get the first sibling after "#golden-delicious" with class name "yummy":

    $('golden-delicious').next('.yummy');
    // -> li#mcintosh
    

    Get the second sibling after "#golden-delicious" with class name "yummy":

    $('golden-delicious').next('.yummy', 1);
    // -> li#ida-red
    

    Try to get the first sibling after "#ida-red":

    $('ida-red').next();
    // -> undefined   

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.nextSiblings

      • Element.nextSiblings(element)

    Collects all of element's next siblings and returns them as an Array of elements.

    Two elements are siblings if they have the same parent. So for example, the head and body elements are siblings (their parent is the html element). Next-siblings are simply the ones which follow element in the document.

    The returned Array reflects the siblings order in the document (e.g. an index of 0 refers to the sibling right below element).

    Note that all of Prototype's DOM traversal methods ignore text nodes and return element nodes only.

    Examples
    language: html
    <ul>
      <li id="golden-delicious">Golden Delicious</li>
      <li id="mutsu">Mutsu</li>
      <li id="mcintosh">McIntosh</li>
      <li id="ida-red">Ida Red</li>
    </ul>
    

    Then:

    $('mutsu').nextSiblings();
    // -> [li#mcintosh, li#ida-red]
    
    $('ida-red').nextSiblings();
    // -> []

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.observe

      • Element.observe(element, eventName, handler)

    See Event.observe.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.on

      • Element.on(element, eventName[, selector], callback)

    See Event.on.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.positionedOffset

      • Element.positionedOffset(element)

    Returns element's offset relative to its closest positioned ancestor (the element that would be returned by Element.getOffsetParent).

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.previous

      • Element.previous
      • Element.previous(element[, index = 0])
      • expression
        • String
      • A CSS selector.

    Returns element's first previous sibling (or the Nth, if index is specified) that matches expression. If no expression is provided, all previous siblings are considered. If none matches these criteria, undefined is returned.

    More information

    The Element.previous method is part of Prototype's ultimate DOM traversal toolkit (check out Element.up, Element.down and Element.next for some more Prototypish niceness). It allows precise index-based and/or CSS expression-based selection of any of element's previous siblings. (Note that two elements are considered siblings if they have the same parent, so for example, the head and body elements are siblings—their parent is the html element.)

    As it totally ignores text nodes (it only returns elements), you don't have to worry about whitespace nodes.

    And as an added bonus, all elements returned are already extended (see Element.extend) allowing chaining:

    $(element).down('p').previous('ul', 2).hide();
    

    Walking the DOM has never been that easy!

    Arguments

    If no arguments are passed, element's previous sibling is returned (this is similar as calling previousSibling except Element.previous returns an already extended element).

    If index is defined, element's corresponding previous sibling is returned. (This is equivalent to selecting an element from the array of elements returned by the method Element.previousSiblings). Note that the sibling right above element has an index of 0.

    If expression is defined, Element.previous will return the element first previous sibling that matches it.

    If both expression and index are defined, Element.previous will collect all of element's previous siblings matching the given CSS expression and will return the one at the specified index.

    In all of the above cases, if no previous sibling is found, undefined will be returned.

    Examples
    language: html
    <ul id="fruits">
      <li id="apples">
        <h3>Apples</h3>
        <ul id="list-of-apples">
          <li id="golden-delicious" class="yummy">Golden Delicious</li>
          <li id="mutsu" class="yummy">Mutsu</li>
          <li id="mcintosh">McIntosh</li>
          <li id="ida-red">Ida Red</li>
        </ul>
        <p id="saying">An apple a day keeps the doctor away.</p>  
      </li>
    </ul>
    

    Get the first previous sibling of "#saying":

    $('saying').previous();
    // or:
    $('saying').previous(0);
    // -> ul#list-of-apples
    

    Get the second previous sibling of "#saying":

    $('saying').previous(1);
    // -> h3
    

    Get the first previous sibling of "#saying" with node name "h3":

    $('saying').previous('h3');
    // -> h3
    

    Get the first previous sibling of "#ida-red" with class name "yummy":

    $('ida-red').previous('.yummy');
    // -> li#mutsu
    

    Get the second previous sibling of "#ida-red" with class name "yummy":

    $('ida-red').previous('.yummy', 1);
    // -> li#golden-delicious
    

    Try to get the sixth previous sibling of "#ida-red":

    $('ida-red').previous(5);
    // -> undefined

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.previousSiblings

      • Element.previousSiblings(element)

    Collects all of element's previous siblings and returns them as an Array of elements.

    Two elements are siblings if they have the same parent. So for example, the <head> and <body> elements are siblings (their parent is the <html> element). Previous-siblings are simply the ones which precede element in the document.

    The returned Array reflects the siblings inversed order in the document (e.g. an index of 0 refers to the lowest sibling i.e., the one closest to element).

    Note that all of Prototype's DOM traversal methods ignore text nodes and return element nodes only.

    Examples
    language: html
    <ul>
      <li id="golden-delicious">Golden Delicious</li>
      <li id="mutsu">Mutsu</li>
      <li id="mcintosh">McIntosh</li>
      <li id="ida-red">Ida Red</li>
    </ul>
    

    Then:

    $('mcintosh').previousSiblings();
    // -> [li#mutsu, li#golden-delicious]
    
    $('golden-delicious').previousSiblings();
    // -> []

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.purge

      • Element.purge(element)
        • null

    Removes all event listeners and storage keys from an element.

    To be used just before removing an element from the page.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.readAttribute

      • Element.readAttribute(element, attributeName)

    Returns the value of element's attribute or null if attribute has not been specified.

    This method serves two purposes. First it acts as a simple wrapper around getAttribute which isn't a "real" function in Safari and Internet Explorer (it doesn't have .apply or .call for instance). Secondly, it cleans up the horrible mess Internet Explorer makes when handling attributes.

    Examples
    language: html
    <a id="tag" href="/tags/prototype" rel="tag" title="view related bookmarks." my_widget="some info.">Prototype</a>
    

    Then:

    $('tag').readAttribute('href');
    // -> '/tags/prototype'
    
    $('tag').readAttribute('title');
    // -> 'view related bookmarks.'
    
    $('tag').readAttribute('my_widget');
    // -> 'some info.'

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.recursivelyCollect

      • Element.recursivelyCollect(element, property)

    Recursively collects elements whose relationship to element is specified by property. property has to be a property (a method won't do!) of element that points to a single DOM node (e.g., nextSibling or parentNode).

    More information

    This method is used internally by Element.ancestors, Element.descendants, Element.nextSiblings, Element.previousSiblings and Element.siblings which offer really convenient way to grab elements, so directly accessing Element.recursivelyCollect should seldom be needed. However, if you are after something out of the ordinary, it is the way to go.

    Note that all of Prototype's DOM traversal methods ignore text nodes and return element nodes only.

    Examples
    language: html
    <ul id="fruits">
      <li id="apples">
        <ul id="list-of-apples">
          <li id="golden-delicious"><p>Golden Delicious</p></li>
          <li id="mutsu">Mutsu</li>
          <li id="mcintosh">McIntosh</li>
          <li id="ida-red">Ida Red</li>
        </ul>
      </li>
    </ul>
    

    And the associated JavaScript:

    $('fruits').recursivelyCollect('firstChild');
    // -> [li#apples, ul#list-of-apples, li#golden-delicious, p]

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.relativize

    Turns element into a relatively-positioned element without changing its position in the page layout.

    Used to undo a call to Element.absolutize.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.remove

    Completely removes element from the document and returns it.

    If you would rather just hide the element and keep it around for further use, try Element.hide instead.

    Examples
    language: html
    // Before:
    <ul>
      <li id="golden-delicious">Golden Delicious</li>
      <li id="mutsu">Mutsu</li>
      <li id="mcintosh">McIntosh</li>
      <li id="ida-red">Ida Red</li>
    </ul>
    

    And the associated JavaScript:

    $('mutsu').remove();
    // -> Element (and removes li#mutsu)
    

    The resulting HTML:

    language: html
    <ul>
      <li id="golden-delicious">Golden Delicious</li>
      <li id="mcintosh">McIntosh</li>
      <li id="ida-red">Ida Red</li>
    </ul>

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.removeClassName

      • Element.removeClassName(element, className)

    Removes CSS class className from element.

    Examples

    Assuming this HTML:

    language: html
    <div id="mutsu" class="apple fruit food"></div>
    

    Then:

    $('mutsu').removeClassName('food');
    // -> Element
    
    $('mutsu').classNames;
    // -> 'apple fruit'

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.replace

      • Element.replace(element[, newContent])

    Replaces element itself with newContent and returns element.

    Keep in mind that this method returns the element that has just been removed — not the element that took its place.

    newContent can be either plain text, an HTML snippet or any JavaScript object which has a toString() method.

    If newContent contains any <script> tags, these will be evaluated after element has been replaced (Element.replace internally calls String#evalScripts).

    Note that if no argument is provided, Element.replace will simply clear element of its content. However, using Element.remove to do so is both faster and more standard compliant.

    Examples
    language: html
    <div id="food">
      <div id="fruits">
        <p id="first">Kiwi, banana <em>and</em> apple.</p>
      </div>
    </div>
    

    Passing an HTML snippet:

    $('first').replace('<ul id="favorite"><li>kiwi</li><li>banana</li><li>apple</li></ul>');
    // -> Element (p#first)
    
    $('fruits').innerHTML;
    // -> '<ul id="favorite"><li>kiwi</li><li>banana</li><li>apple</li></ul>'
    

    Again, with a <script> tag thrown in:

    $('favorite').replace('<p id="still-first">Melon, oranges <em>and</em> grapes.</p><script>alert("removed!")</script>');
    // -> Element (ul#favorite) and prints "removed!" in an alert dialog.
    
    $('fruits').innerHTML;
    // -> '<p id="still-first">Melon, oranges <em>and</em> grapes.</p>'
    

    With plain text:

    $('still-first').replace('Melon, oranges and grapes.');
    // -> Element (p#still-first)
    
    $('fruits').innerHTML;
    // -> 'Melon, oranges and grapes.'
    

    Finally, relying on the toString() method:

    $('fruits').replace(123);
    // -> Element
    
    $('food').innerHTML;
    // -> '123'
    
    Warning

    Using Element.replace as an instance method (e.g., $('foo').replace('<p>Bar</p>')) causes errors in Opera 9 when used on input elements. The replace property is reserved on input elements as part of Web Forms 2. As a workaround, use the generic version instead (Element.replace('foo', '<p>Bar</p>')).

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.retrieve

      • Element.retrieve(element, key[, defaultValue])
        • ?

    Retrieves custom metadata set on element with Element.store.

    If the value is undefined and defaultValue is given, it will be stored on the element as its new value for that key, then returned.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.scrollTo

    Scrolls the window so that element appears at the top of the viewport.

    This has a similar effect than what would be achieved using HTML anchors (except the browser's history is not modified).

    Example
    $(element).scrollTo();
    // -> Element

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.select

      • Element.select(element, expression...)
      • expression
        • String
      • A CSS selector.

    Takes an arbitrary number of CSS selectors and returns an array of descendants of element that match any of them.

    This method is very similar to $$ but can be used within the context of one element, rather than the whole document. The supported CSS syntax is identical, so please refer to the $$ docs for details.

    Examples
    language: html
    <ul id="fruits">
      <li id="apples">
        <h3 title="yummy!">Apples</h3>
        <ul id="list-of-apples">
          <li id="golden-delicious" title="yummy!" >Golden Delicious</li>
          <li id="mutsu" title="yummy!">Mutsu</li>
          <li id="mcintosh">McIntosh</li>
          <li id="ida-red">Ida Red</li>
        </ul>
        <p id="saying">An apple a day keeps the doctor away.</p>  
      </li>
    </ul>
    

    Then:

    $('apples').select('[title="yummy!"]');
    // -> [h3, li#golden-delicious, li#mutsu]
    
    $('apples').select( 'p#saying', 'li[title="yummy!"]');
    // -> [li#golden-delicious, li#mutsu,  p#saying]
    
    $('apples').select('[title="disgusting!"]');
    // -> []
    
    Tip

    Element.select can be used as a pleasant alternative to the native method getElementsByTagName:

    var nodes  = $A(someUL.getElementsByTagName('li')).map(Element.extend);
    var nodes2 = someUL.select('li');
    

    In the first example, you must explicitly convert the result set to an Array (so that Prototype's Enumerable methods can be used) and must manually call Element.extend on each node (so that custom instance methods can be used on the nodes). Element.select takes care of both concerns on its own.

    If you're using 1.6 or above (and the performance optimizations therein), the speed difference between these two examples is negligible.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.setOpacity

      • Element.setOpacity(element, opacity)

    Sets the visual opacity of an element while working around inconsistencies in various browsers. The opacity argument should be a floating point number, where the value of 0 is fully transparent and 1 is fully opaque.

    Element.setStyle method uses Element.setOpacity internally when needed.

    Examples
    var element = $('myelement');
    // set to 50% transparency
    element.setOpacity(0.5);
    
    // these are equivalent, but allow for setting more than
    // one CSS property at once:
    element.setStyle({ opacity: 0.5 });
    element.setStyle("opacity: 0.5");

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.setStyle

      • Element.setStyle(element, styles)

    Modifies element's CSS style properties. Styles are passed as a hash of property-value pairs in which the properties are specified in their camelized form.

    Examples
    $(element).setStyle({
      backgroundColor: '#900',
      fontSize: '12px'
    });
    // -> Element
    
    Notes

    The method transparently deals with browser inconsistencies for float (however, as float is a reserved keyword, you must either escape it or use cssFloat instead) and opacity (which accepts values between 0 -fully transparent- and 1 -fully opaque-). You can safely use either of the following across all browsers:

    $(element).setStyle({
      cssFloat: 'left',
      opacity: 0.5
    });
    // -> Element
    
    $(element).setStyle({
      'float': 'left', // notice how float is surrounded by single quotes
      opacity: 0.5
    });
    // -> Element
    

    Not all CSS shorthand properties are supported. You may only use the CSS properties described in the Document Object Model (DOM) Level 2 Style Specification.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.show

    Removes display: none on element. Returns element.

    Examples

    Show a single element:

    <div id="error-message" style="display:none;"></div>
    
    $('error-message').show();
    // -> Element (and displays div#error-message)
    

    Show multiple elements using Enumerable#each:

    ['content', 'navigation', 'footer'].each(Element.show);
    // -> ['content', 'navigation', 'footer'] 
    

    Show multiple elements using Enumerable#invoke:

    $('content', 'navigation', 'footer').invoke('show');
    // -> [Element, Element, Element]
    
    Notes

    Element.show cannot display elements hidden via CSS stylesheets. Note that this is not a Prototype limitation but a consequence of how the CSS display property works.

    <style>
      #hidden-by-css {
        display: none;
      }
    </style>
    
    [...]
    
    <div id="hidden-by-css"></div>
    
    $('hidden-by-css').show(); // DOES NOT WORK!
    // -> Element (div#error-message is still hidden!)

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.siblings

      • Element.siblings(element)

    Collects all of element's siblings and returns them as an Array of elements.

    Two elements are siblings if they have the same parent. So for example, the head and body elements are siblings (their parent is the html element).

    The returned Array reflects the siblings' order in the document (e.g. an index of 0 refers to element's topmost sibling).

    Note that all of Prototype's DOM traversal methods ignore text nodes and return element nodes only.

    Examples
    language: html
    <ul>
      <li id="golden-delicious">Golden Delicious</li>
      <li id="mutsu">Mutsu</li>
      <li id="mcintosh">McIntosh</li>
      <li id="ida-red">Ida Red</li>
    </ul>
    

    Then:

    $('mutsu').siblings();
    // -> [li#golden-delicious, li#mcintosh, li#ida-red]

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.stopObserving

      • Element.stopObserving(element[, eventName][, handler])

    See Event.stopObserving.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.store

      • Element.store(element, key, value)

    Stores a key/value pair of custom metadata on the element.

    The metadata can later be retrieved with Element.retrieve.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.toggle

      • Element.toggle(element[, bool])

    Toggles the CSS display of element. Returns element.

    Switches an element's CSS display between none and its inherited value (usually block or inline).

    By default, toggle will switch the display to the opposite of its current state, but will use the bool argument instead if it's provided (true to show the element, false to hide it).

    Examples
    <div id="welcome-message"></div>
    <div id="error-message" style="display:none;"></div>
    
    $('welcome-message').toggle();
    // -> Element (and hides div#welcome-message)
    
    $('error-message').toggle();
    // -> Element (and displays div#error-message)
    
    $('error-message).toggle(true);
    // -> Element (and displays div#error-message, no matter what its
    //    previous state)
    

    Toggle multiple elements using Enumerable#each:

    ['error-message', 'welcome-message'].each(Element.toggle);
    // -> ['error-message', 'welcome-message'] 
    

    Toggle multiple elements using Enumerable#invoke:

    $('error-message', 'welcome-message').invoke('toggle');
    // -> [Element, Element]
    
    $('error-message', 'welcome-message').invoke('toggle', false);
    // -> [Element, Element] (and hides both elements, no matter what
          their previous state)
    
    Notes

    Element.toggle cannot display elements hidden via CSS stylesheets. Note that this is not a Prototype limitation but a consequence of how the CSS display property works.

    <style>
      #hidden-by-css {
        display: none;
      }
    </style>
    
    [...]
    
    <div id="hidden-by-css"></div>
    
    $('hidden-by-css').toggle(); // WON'T WORK!
    // -> Element (div#hidden-by-css is still hidden!)

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.toggleClassName

      • Element.toggleClassName(element, className[, bool])

    Toggles the presence of CSS class className on element.

    By default, toggleClassName will flip to the opposite state, but will use bool instead if it's given; true will add the class name and false will remove it.

    Examples
    language: html
    <div id="mutsu" class="apple"></div>
    

    Then:

    $('mutsu').hasClassName('fruit');
    // -> false
    
    $('mutsu').toggleClassName('fruit');
    // -> Element
    
    $('mutsu').hasClassName('fruit');
    // -> true
    
    $('mutsu').toggleClassName('fruit', true);
    // -> Element (keeps the "fruit" class name that was already there)

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.undoClipping

      • Element.undoClipping(element)

    Sets element's CSS overflow property back to the value it had before Element.makeClipping was applied.

    Example
    language: html
    <div id="framer">
      <img src="/assets/2007/1/14/chairs.jpg" alt="example" />
    </div>
    

    Then:

    $('framer').undoClipping();
    // -> Element (and sets the CSS overflow property to its original value).
    

    Another example:

    language: html
    <a id="clipper" href="#">Click me to try it out.</a>
    
    <div id="framer">
      <img src="/assets/2007/2/24/chairs_1.jpg" alt="example" />
    </div>
    
    <script type="text/javascript" charset="utf-8">
      var Example = {
        clip: function(){
          $('clipper').update('undo clipping!');
          $('framer').makeClipping().setStyle({width: '100px', height: '100px'});
        },
        unClip: function(){
          $('clipper').update('clip!');
          $('framer').undoClipping();
        },
        toggleClip: function(event){
          if($('clipper').innerHTML == 'clip!') Example.clip();
          else Example.unClip();
          Event.stop(event);
        }
      };
      $('framer').makeClipping().setStyle({width: '100px', height: '100px'});
      Event.observe('clipper', 'click', Example.toggleClip);
    </script>

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.undoPositioned

      • Element.undoPositioned(element)

    Sets element back to the state it was in before Element.makePositioned was applied to it.

    element's absolutely positioned children will now have their positions set relatively to element's nearest ancestor with a CSS position of 'absolute', 'relative' or 'fixed'.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.up

      • Element.up
      • Element.up(element[, index = 0])
      • expression
        • String
      • A CSS selector.

    Returns element's first ancestor (or the Nth ancestor, if index is specified) that matches expression. If no expression is provided, all ancestors are considered. If no ancestor matches these criteria, undefined is returned.

    More information

    The Element.up method is part of Prototype's ultimate DOM traversal toolkit (check out Element.down, Element.next and Element.previous for some more Prototypish niceness). It allows precise index-based and/or CSS rule-based selection of any of element's ancestors.

    As it totally ignores text nodes (it only returns elements), you don't have to worry about whitespace nodes.

    And as an added bonus, all elements returned are already extended (see [[Element.extended]]) allowing chaining:

    $(element).up(1).next('li', 2).hide();
    

    Walking the DOM has never been that easy!

    Arguments

    If no arguments are passed, element's first ancestor is returned (this is similar to calling parentNode except Element.up returns an already extended element.

    If index is defined, element's corresponding ancestor is returned. (This is equivalent to selecting an element from the array of elements returned by the method Element.ancestors). Note that the first element has an index of 0.

    If expression is defined, Element.up will return the first ancestor that matches it.

    If both expression and index are defined, Element.up will collect all the ancestors matching the given CSS expression and will return the one at the specified index.

    In all of the above cases, if no descendant is found, undefined will be returned.

    Examples

    language: html
    <html>
      [...]
      <body>
        <ul id="fruits">
          <li id="apples" class="keeps-the-doctor-away">
            <ul>
              <li id="golden-delicious">Golden Delicious</li>
              <li id="mutsu" class="yummy">Mutsu</li>
              <li id="mcintosh" class="yummy">McIntosh</li>
              <li id="ida-red">Ida Red</li>
            </ul>
          </li>
        </ul>
      </body>
    </html>
    

    Get the first ancestor of "#fruites":

    $('fruits').up();
    // or:
    $('fruits').up(0);
    // -> body
    

    Get the third ancestor of "#mutsu":

    $('mutsu').up(2);
    // -> ul#fruits
    

    Get the first ancestor of "#mutsu" with the node name "li":

    $('mutsu').up('li');
    // -> li#apples
    

    Get the first ancestor of "#mutsu" with the class name "keeps-the-doctor-away":

    $('mutsu').up('.keeps-the-doctor-away');
    // -> li#apples
    

    Get the second ancestor of "#mutsu" with the node name "ul":

    $('mutsu').up('ul', 1);
    // -> ul#fruits
    

    Try to get the first ancestor of "#mutsu" with the node name "div":

    $('mutsu').up('div');
    // -> undefined

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.update

      • Element.update(element[, newContent])

    Replaces the content of element with the newContent argument and returns element.

    newContent may be in any of these forms:

    • String: A string of HTML to be parsed and rendered
    • Element: An Element instance to insert
    • ...any object with a toElement method: The method is called and the resulting element used
    • ...any object with a toHTML method: The method is called and the resulting HTML string is parsed and rendered

    If newContent is omitted, the element's content is blanked out (i.e., replaced with an empty string).

    If newContent is a string and contains one or more inline <script> tags, the scripts are scheduled to be evaluated after a very brief pause (using Function#defer) to allow the browser to finish updating the DOM. Note that the scripts are evaluated in the scope of String#evalScripts, not in the global scope, which has important ramifications for your vars and functions. See String#evalScripts for details.

    Note that this method allows seamless content update of table related elements in Internet Explorer 6 and beyond.

    Any nodes replaced with Element.update will first have event listeners unregistered and storage keys removed. This frees up memory and prevents leaks in certain versions of Internet Explorer. (See Element.purge).

    Examples
    language: html
    <div id="fruits">carrot, eggplant and cucumber</div>
    

    Passing a regular string:

    $('fruits').update('kiwi, banana and apple');
    // -> Element
    $('fruits').innerHTML;
    // -> 'kiwi, banana and apple'
    

    Clearing the element's content:

    $('fruits').update();
    // -> Element
    $('fruits').innerHTML;
    // -> '' (an empty string)
    

    And now inserting an HTML snippet:

    $('fruits').update('<p>Kiwi, banana <em>and</em> apple.</p>');
    // -> Element
    $('fruits').innerHTML;
    // -> '<p>Kiwi, banana <em>and</em> apple.</p>'
    

    ... with a <script> tag thrown in:

    $('fruits').update('<p>Kiwi, banana <em>and</em> apple.</p><script>alert("updated!")</script>');
    // -> Element (and prints "updated!" in an alert dialog).
    $('fruits').innerHTML;
    // -> '<p>Kiwi, banana <em>and</em> apple.</p>'
    

    Relying on the toString() method:

    $('fruits').update(123);
    // -> Element
    $('fruits').innerHTML;
    // -> '123'
    

    Finally, you can do some pretty funky stuff by defining your own toString() method on your custom objects:

    var Fruit = Class.create({
      initialize: function(fruit){
        this.fruit = fruit;
      },
      toString: function(){
        return 'I am a fruit and my name is "' + this.fruit + '".'; 
      }
    });
    var apple = new Fruit('apple');
    
    $('fruits').update(apple);
    $('fruits').innerHTML;
    // -> 'I am a fruit and my name is "apple".'

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.viewportOffset

      • Element.viewportOffset(element)

    Returns the X/Y coordinates of element relative to the viewport.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.visible

      • Element.visible(element)
        • Boolean

    Tells whether element is visible (i.e., whether its inline display CSS property is set to none.

    Examples
    language: html
    <div id="visible"></div>
    <div id="hidden" style="display: none;"></div>
    

    And the associated JavaScript:

    $('visible').visible();
    // -> true
    
    $('hidden').visible();
    // -> false
    
    Notes

    Styles applied via a CSS stylesheet are not taken into consideration. Note that this is not a Prototype limitation, it is a CSS limitation.

    language: html
    <style>
      #hidden-by-css {
        display: none;
      }
    </style>
    
    [...]
    
    <div id="hidden-by-css"></div>
    

    And the associated JavaScript:

    $('hidden-by-css').visible();
    // -> true

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.wrap

      • Element.wrap(element, wrapper[, attributes])
      • wrapper
        • Element
        • String
      • An element to wrap element inside, or else a string representing the tag name of an element to be created.

      • attributes
        • Object
      • A set of attributes to apply to the wrapper element. Refer to the Element constructor for usage.

    Wraps an element inside another, then returns the wrapper.

    If the given element exists on the page, Element.wrap will wrap it in place — its position will remain the same.

    The wrapper argument can be either an existing Element or a string representing the tag name of an element to be created. The optional attributes argument can contain a list of attribute/value pairs that will be set on the wrapper using Element.writeAttribute.

    Examples

    Original HTML:

    language: html
    <table id="data">
      <tr>
        <th>Foo</th>
        <th>Bar</th>
      </tr>
      <tr>
        <td>1</td>
        <td>2</td>
      </tr>
    </table>
    

    JavaScript:

    // approach 1:
    var div = new Element('div', { 'class': 'table-wrapper' });
    $('data').wrap(div);
    
    // approach 2:
    $('data').wrap('div', { 'class': 'table-wrapper' });
    
    // Both examples are equivalent &mdash; they return the DIV.
    

    Resulting HTML:

    language: html
    <div class="table-wrapper">
      <table id="data">
        <tr>
          <th>Foo</th>
          <th>Bar</th>
        </tr>
        <tr>
          <td>1</td>
          <td>2</td>
        </tr>
      </table>
    </div> 
    
    Warning

    Using Element.wrap as an instance method (e.g., $('foo').wrap('p')) causes errors in Internet Explorer when used on textarea elements. The wrap property is reserved on textarea's as a proprietary extension to HTML. As a workaround, use the generic version instead (Element.wrap('foo', 'p')).

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element.writeAttribute

      • Element.writeAttribute
      • Element.writeAttribute(element, attributes)

    Adds, specifies or removes attributes passed as either a hash or a name/value pair.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#absolutize

    Turns element into an absolutely-positioned element without changing its position in the page layout.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#addClassName

      • Element#addClassName(className)
      • className
        • String
      • The class name to add.

    Adds the given CSS class to element.

    Example

    Assuming this HTML:

    language: html
    <div id="mutsu" class="apple fruit"></div>
    

    Then:

    $('mutsu').className;
    // -> 'apple fruit'
    $('mutsu').addClassName('food');
    $('mutsu').className;
    // -> 'apple fruit food'

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#adjacent

      • Element#adjacent(selector...)
      • selector
        • String
      • A CSS selector.

    Finds all siblings of the current element that match the given selector(s). If you provide multiple selectors, siblings matching any of the selectors are included. If a sibling matches multiple selectors, it is only included once. The order of the returned array is not defined.

    Example

    Assuming this list:

    language: html
    <ul id="cities">
      <li class="us" id="nyc">New York</li>
      <li class="uk" id="lon">London</li>
      <li class="us" id="chi">Chicago</li>
      <li class="jp" id="tok">Tokyo</li>
      <li class="us" id="la">Los Angeles</li>
      <li class="us" id="aus">Austin</li>
    </ul>
    

    Then:

    $('nyc').adjacent('li.us');
    // -> [li#chi, li#la, li#aus]
    $('nyc').adjacent('li.uk', 'li.jp');
    // -> [li#lon, li#tok]

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#ancestors

    Collects all of element's ancestor elements and returns them as an array of extended elements.

    The returned array's first element is element's direct ancestor (its parentNode), the second one is its grandparent, and so on until the <html> element is reached. <html> will always be the last member of the array. Calling ancestors on the <html> element will return an empty array.

    Example

    Assuming:

    language: html
    <html>
    [...]
      <body>
        <div id="father">
          <div id="kid">
          </div>
        </div>
      </body>
    </html>
    

    Then:

    $('kid').ancestors();
    // -> [div#father, body, html]

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#childElements

      • Element#childElements()

    Collects all of the element's children and returns them as an array of [[Element.extended extended]] elements, in document order. The first entry in the array is the topmost child of element, the next is the child after that, etc.

    Like all of Prototype's DOM traversal methods, Element.childElements ignores text nodes and returns element nodes only.

    Example

    Assuming:

    language: html
    <div id="australopithecus">
      Some text in a text node
      <div id="homo-erectus">
        <div id="homo-neanderthalensis"></div>
        <div id="homo-sapiens"></div>
      </div>
    </div>
    

    Then:

    $('australopithecus').childElements();
    // -> [div#homo-erectus]
    
    $('homo-erectus').childElements();
    // -> [div#homo-neanderthalensis, div#homo-sapiens]
    
    $('homo-sapiens').childElements();
    // -> []

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#classNames

    Deprecated
      • Element#classNames()

    Returns a new instance of [[Element.ClassNames]], an Enumerable object used to read and write CSS class names of element.

    Deprecated, please see Element.addClassName, Element.removeClassName, and Element.hasClassName. If you want an array of classnames, you can use $w(element.className).

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#cleanWhitespace

    Removes all of element's child text nodes that contain only whitespace. Returns element.

    This can be very useful when using standard properties like nextSibling, previousSibling, firstChild or lastChild to walk the DOM. Usually you'd only do that if you are interested in all of the DOM nodes, not just Elements (since if you just need to traverse the Elements in the DOM tree, you can use Element.up, Element.down, Element.next, and Element.previous instead).

    Example

    Consider the following HTML snippet:

    language: html
    <ul id="apples">
      <li>Mutsu</li>
      <li>McIntosh</li>
      <li>Ida Red</li>
    </ul>
    

    Let's grab what we think is the first list item using the raw DOM method:

    var element = $('apples');
    element.firstChild.innerHTML;
    // -> undefined
    

    It's undefined because the firstChild of the apples element is a text node containing the whitespace after the end of the ul and before the first li.

    If we remove the useless whitespace, then firstChild works as expected:

    var element = $('apples');
    element.cleanWhitespace();
    element.firstChild.innerHTML;
    // -> 'Mutsu'

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#clone

      • deep
        • Boolean
      • Whether to clone element's descendants as well.

    Returns a duplicate of element.

    A wrapper around DOM Level 2 Node#cloneNode, Element.clone cleans up any expando properties defined by Prototype.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#clonePosition

      • Element#clonePosition(source[, options])
      • source
        • Element
        • String
      • The source element (or its ID).

      • options
        • Object
      • The position fields to clone.

    Clones the position and/or dimensions of source onto the element as defined by options, with an optional offset for the left and top properties.

    Note that the element will be positioned exactly like source whether or not it is part of the same CSS containing block.

    Options

    <table class='options'> <thead> <tr> <th style='text-align: left; padding-right: 1em'>Name</th> <th style='text-align: left; padding-right: 1em'>Default</th> <th style='text-align: left; padding-right: 1em'>Description</th> </tr> </thead> <tbody> <tr> <td><code>setLeft</code></td> <td><code>true</code></td> <td>Clones <code>source</code>'s <code>left</code> CSS property onto <code>element</code>.</td> </tr> <tr> <td><code>setTop</code></td> <td><code>true</code></td> <td>Clones <code>source</code>'s <code>top</code> CSS property onto <code>element</code>.</td> </tr> <tr> <td><code>setWidth</code></td> <td><code>true</code></td> <td>Clones <code>source</code>'s <code>width</code> onto <code>element</code>.</td> </tr> <tr> <td><code>setHeight</code></td> <td><code>true</code></td> <td>Clones <code>source</code>'s <code>width</code> onto <code>element</code>.</td> </tr> <tr> <td><code>offsetLeft</code></td> <td><code>0</code></td> <td>Number by which to offset <code>element</code>'s <code>left</code> CSS property.</td> </tr> <tr> <td><code>offsetTop</code></td> <td><code>0</code></td> <td>Number by which to offset <code>element</code>'s <code>top</code> CSS property.</td> </tr> </tbody> </table>

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#cumulativeOffset

      • Element#cumulativeOffset()

    Returns the offsets of element from the top left corner of the document.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#cumulativeScrollOffset

      • Element#cumulativeScrollOffset()

    Calculates the cumulative scroll offset of an element in nested scrolling containers.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#descendantOf

      • Element#descendantOf(ancestor)
        • Boolean
      • ancestor
        • Element
        • String
      • The element to check against (or its ID).

    Checks if element is a descendant of ancestor.

    Example

    Assuming:

    language: html
    <div id="australopithecus">
      <div id="homo-erectus">
        <div id="homo-sapiens"></div>
      </div>
    </div>
    

    Then:

    $('homo-sapiens').descendantOf('australopithecus');
    // -> true
    
    $('homo-erectus').descendantOf('homo-sapiens');
    // -> false

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#descendants

      • Element#descendants()

    Collects all of the element's descendants (its children, their children, etc.) and returns them as an array of extended elements. As with all of Prototype's DOM traversal methods, only Elements are returned, other nodes (text nodes, etc.) are skipped.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#down

      • Element#down
      • expression
        • String
      • A CSS selector.

    Returns element's first descendant (or the Nth descendant, if index is specified) that matches expression. If no expression is provided, all descendants are considered. If no descendant matches these criteria, undefined is returned.

    More information

    The Element.down method is part of Prototype's ultimate DOM traversal toolkit (check out Element.up, Element.next and Element.previous for some more Prototypish niceness). It allows precise index-based and/or CSS rule-based selection of any of the element's descendants.

    As it totally ignores text nodes (it only returns elements), you don't have to worry about whitespace nodes.

    And as an added bonus, all elements returned are already extended (see Element.extend) allowing chaining:

    $(element).down(1).next('li', 2).hide();
    

    Walking the DOM has never been that easy!

    Arguments

    If no arguments are passed, element's first descendant is returned (this is similar to calling firstChild except Element.down returns an extended element.

    If index is defined, element's corresponding descendant is returned. (This is equivalent to selecting an element from the array of elements returned by the method Element.descendants.) Note that the first element has an index of 0.

    If expression is defined, Element.down will return the first descendant that matches it. This is a great way to grab the first item in a list for example (just pass in 'li' as the method's first argument).

    If both expression and index are defined, Element.down will collect all the descendants matching the given CSS expression and will return the one at the specified index.

    In all of the above cases, if no descendant is found, undefined will be returned.

    Examples
    language: html
    <ul id="fruits">
      <li id="apples">
        <ul>
          <li id="golden-delicious">Golden Delicious</li>
          <li id="mutsu" class="yummy">Mutsu</li>
          <li id="mcintosh" class="yummy">McIntosh</li>
          <li id="ida-red">Ida Red</li>
        </ul>
      </li>
    </ul>
    

    Get the first descendant of "#fruites":

    $('fruits').down();
    // or:
    $('fruits').down(0);
    // -> li#apples
    

    Get the third descendant of "#fruits":

    $('fruits').down(3);
    // -> li#golden-delicious
    

    Get the first descendant of "#apples" with the node name "li":

    $('apples').down('li');
    // -> li#golden-delicious
    

    Get the first descendant of "#apples" with the node name "li" and the class name "yummy":

    $('apples').down('li.yummy');
    // -> li#mutsu
    

    Get the second descendant of "#fruits" with the class name "yummy":

    $('fruits').down('.yummy', 1);
    // -> li#mcintosh
    

    Try to get the ninety-ninth descendant of "#fruits":

    $('fruits').down(99);
    // -> undefined

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#empty

    Tests whether element is empty (i.e., contains only whitespace).

    Examples
    <div id="wallet">     </div>
    <div id="cart">full!</div>
    
    $('wallet').empty();
    // -> true
    
    $('cart').empty();
    // -> false

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#fire

      • Element#fire(eventName[, memo][, bubble = true])

    See Event.fire.

    Fires a custom event with the current element as its target.

    Element.fire creates a custom event with the given name, then triggers it on the given element. The custom event has all the same properties and methods of native events. Like a native event, it will bubble up through the DOM unless its propagation is explicitly stopped.

    The optional second argument will be assigned to the memo property of the event object so that it can be read by event handlers.

    Custom events are dispatched synchronously: Element.fire waits until the event finishes its life cycle, then returns the event itself.

    Note

    Element.fire does not support firing native events. All custom event names must be namespaced (using a colon). This is to avoid custom event names conflicting with non-standard native DOM events such as mousewheel and DOMMouseScroll.

    Examples
    document.observe("widget:frobbed", function(event) {
      console.log("Element with ID (" + event.target.id +
       ") frobbed widget #" + event.memo.widgetNumber + ".");
    });
    
    var someNode = $('foo');
    someNode.fire("widget:frobbed", { widgetNumber: 19 });
    
    //-> "Element with ID (foo) frobbed widget #19."
    
    Tip

    Events that have been stopped with Event.stop will have a boolean stopped property set to true. Since Element.fire returns the custom event, you can inspect this property to determine whether the event was stopped.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#firstDescendant

    Returns the first child that is an element.

    This is opposed to the firstChild DOM property, which will return any node, including text nodes and comment nodes.

    Examples
    language: html
    <div id="australopithecus">
      <div id="homo-erectus"><!-- Latin is super -->
        <div id="homo-neanderthalensis"></div>
        <div id="homo-sapiens"></div>
      </div>
    </div>
    

    Then:

    $('australopithecus').firstDescendant();
    // -> div#homo-erectus
    
    // the DOM property returns any first node
    $('homo-erectus').firstChild;
    // -> comment node "Latin is super"
    
    // this is what we want!
    $('homo-erectus').firstDescendant();
    // -> div#homo-neanderthalensis

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#getDimensions

    Finds the computed width and height of element and returns them as key/value pairs of an object.

    For backwards-compatibility, these dimensions represent the dimensions of the element's "border box" (including CSS padding and border). This is equivalent to the built-in offsetWidth and offsetHeight browser properties.

    Note that all values are returned as numbers only although they are expressed in pixels.

    Caveats
    • If the element is hidden via display: none in CSS, this method will attempt to measure the element by temporarily removing that CSS and applying visibility: hidden and position: absolute. This gives the element dimensions without making it visible or affecting the positioning of surrounding elements — but may not give accurate results in some cases. Element.measure is designed to give more accurate results.

    • In order to avoid calling the method twice, you should consider caching the returned values in a variable, as shown in the example below.

    • For more complex use cases, use Element.measure, which is able to measure many different aspects of an element's dimensions and offsets.

    Examples
    language: html
    <div id="rectangle" style="font-size: 10px; width: 20em; height: 10em"></div>
    

    Then:

    var dimensions = $('rectangle').getDimensions();
    // -> {width: 200, height: 100}
    
    dimensions.width;
    // -> 200
    
    dimensions.height;
    // -> 100

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#getElementsBySelector

      • Element#getElementsBySelector(selector)

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#getHeight

    Returns the height of element.

    This method returns correct values on elements whose display is set to none either in an inline style rule or in an CSS stylesheet.

    For performance reasons, if you need to query both width and height of element, you should consider using Element.getDimensions instead.

    Note that the value returned is a number only although it is expressed in pixels.

    Examples
    language: html
    <div id="rectangle" style="font-size: 10px; width: 20em; height: 10em"></div>
    

    Then:

    $('rectangle').getHeight();
    // -> 100

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#getLayout

      • Element#getLayout([preCompute = false])
      • element
        • Element
      • The element to be measured.

      • preCompute
        • Boolean
      • Whether to compute all values at once. Default is false.

    Returns an instance of Element.Layout for measuring an element's dimensions.

    Note that this method returns a new Element.Layout object each time it's called. If you want to take advantage of measurement caching, retain a reference to one Element.Layout object, rather than calling Element.getLayout whenever you need a measurement. You should call Element.getLayout again only when the values in an existing Element.Layout object have become outdated.

    If the preCompute argument is true, all properties will be measured when the layout object is instantiated. If you plan to measure several properties of an element's dimensions, it's probably worth it to get a pre-computed hash.

    Examples
    var layout = $('troz').getLayout();
    
    layout.get('width');  //-> 150
    layout.get('height'); //-> 500
    layout.get('padding-left');  //-> 10
    layout.get('margin-left');   //-> 25
    layout.get('border-top');    //-> 5
    layout.get('border-bottom'); //-> 5
    
    // Won't re-compute width; remembers value from first time.
    layout.get('width');  //-> 150
    
    // Composite values obtained by adding together other properties;
    // will re-use any values we've already looked up above.
    layout.get('padding-box-width'); //-> 170
    layout.get('border-box-height'); //-> 510
    
    Caveats
    • Instances of Element.Layout can measure the dimensions of an element hidden with CSS (display: none), but only if its parent element is visible.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#getOffsetParent

    Returns element's closest positioned ancestor. If none is found, the body element is returned.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#getOpacity

      • Element#getOpacity()

    Returns the opacity of the element.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#getStorage

      • Element#getStorage()

    Returns the Hash object that stores custom metadata for this element.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#getStyle

      • Element#getStyle(style)
      • style
        • String
      • The property name to be retrieved.

    Returns the given CSS property value of element. The property can be specified in either its CSS form (font-size) or its camelized form (fontSize).

    This method looks up the CSS property of an element whether it was applied inline or in a stylesheet. It works around browser inconsistencies regarding float, opacity, which returns a value between 0 (fully transparent) and 1 (fully opaque), position properties (left, top, right and bottom) and when getting the dimensions (width or height) of hidden elements.

    Examples
    $(element).getStyle('font-size');
    // equivalent:
    
    $(element).getStyle('fontSize');
    // -> '12px'
    
    Notes

    Not all CSS shorthand properties are supported. You may only use the CSS properties described in the Document Object Model (DOM) Level 2 Style Specification.

    Old versions of Internet Explorer return literal values; other browsers return computed values.

    Consider the following HTML snippet:

    language: html
    <style>
      #test {
        font-size: 12px;
        margin-left: 1em;
      }
    </style>
    <div id="test"></div>
    

    Then:

    $('test').getStyle('margin-left');
    // -> '1em' in Internet Explorer,
    // -> '12px' elsewhere.
    

    Safari returns null for any non-inline property if the element is hidden (has display set to 'none').

    Caveats

    Early versions of Prototype attempted to "fix" this behavior for certain properties. A few examples:

    1. Reading and writing the CSS opacity property works exactly like calling Element.getOpacity and Element.setOpacity respectively. This lets us pretend that IE didn't have a properietary way to set opacity in versions 6-7.
    2. Browsers disagree on how to report certain properties of hidden elements (i.e., display: none). Opera, for instance, says that a hidden element has a width of 0px. It's an arguable point, but we return null in those cases instead (so as to agree with the majority behavior). In short: if an element is hidden, getStyle('width') and getStyle('height') will return null.
    3. In older versions of Internet Explorer, Prototype will return a pixel value for width and height, even if the literal value is a different unit. It does this by treating width like offsetWidth and height like offsetHeight. This is often the incorrect measurement, but it's a mistake we're stuck with for backward-compatibility. If you're trying to measure an element's dimensions, don't use getStyle; use Element.measure instead.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#getWidth

    Returns the width of element.

    This method returns correct values on elements whose display is set to none either in an inline style rule or in an CSS stylesheet.

    For performance reasons, if you need to query both width and height of element, you should consider using Element.getDimensions instead.

    Note that the value returned is a number only although it is expressed in pixels.

    Examples
    language: html
    <div id="rectangle" style="font-size: 10px; width: 20em; height: 10em"></div>
    

    Then:

    $('rectangle').getWidth();
    // -> 200

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#hasClassName

      • Element#hasClassName(className)
        • Boolean

    Checks for the presence of CSS class className on element.

    Examples
    language: html
    <div id="mutsu" class="apple fruit food"></div>
    

    Then:

    $('mutsu').hasClassName('fruit');
    // -> true
    
    $('mutsu').hasClassName('vegetable');
    // -> false

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#hide

    Sets display: none on element. Returns element.

    Examples

    Hide a single element:

    <div id="error-message"></div>
    
    $('error-message').hide();
    // -> Element (and hides div#error-message)
    

    Hide multiple elements using Enumerable#each:

    ['content', 'navigation', 'footer'].each(Element.hide);
    // -> ['content', 'navigation', 'footer'] 
    

    Hide multiple elements using Enumerable#invoke:

    $('content', 'navigation', 'footer').invoke('hide');
    // -> [Element, Element, Element]

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#identify

    Returns element's ID. If element does not have an ID, one is generated, assigned to element, and returned.

    Examples

    Original HTML:

      <ul>
        <li id="apple">apple</li>
        <li>orange</li>
      </ul>
    

    JavaScript:

      $('apple').identify();
      // -> 'apple'
    
      $('apple').next().identify();
      // -> 'anonymous_element_1'
    

    Resulting HTML:

      <ul>
        <li id="apple">apple</li>
        <li id="anonymous_element_1">orange</li>
      </ul>

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#immediateDescendants

    Deprecated
      • Element#immediateDescendants()

    This method is deprecated, please see Element.childElements.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#insert

      • content
        • String
        • Element
        • Object
      • The content to insert.

    Inserts content above, below, at the top, and/or at the bottom of the given element, depending on the option(s) given.

    insert accepts content in any of these forms:

    • String: A string of HTML to be parsed and rendered
    • Element: An Element instance to insert
    • ...any object with a toElement method: The method is called and the resulting element used
    • ...any object with a toHTML method: The method is called and the resulting HTML string is parsed and rendered

    The content argument can be the content to insert, in which case the implied insertion point is bottom, or an object that specifies one or more insertion points (e.g., { bottom: "foo", top: "bar" }).

    Accepted insertion points are:

    • before (as element's previous sibling)
    • after (as element's next sibling)
    • top (as element's first child)
    • bottom (as element's last child)

    Note that if the inserted HTML contains any <script> tag, these will be automatically evaluated after the insertion (insert internally calls [[String.evalScripts]] when inserting HTML).

    <h5>Examples</h5>

    Insert the given HTML at the bottom of the element (using the default):

    $('myelement').insert("<p>HTML to append</p>");
    
    $('myelement').insert({
      top: new Element('img', {src: 'logo.png'})
    });
    

    Put hrs before and after the element:

    $('myelement').insert({
      before: "<hr>",
      after: "<hr>"
    });

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#inspect

    Returns the debug-oriented string representation of element.

    For more information on inspect methods, see Object.inspect.

    language: html
    <ul>
      <li id="golden-delicious">Golden Delicious</li>
      <li id="mutsu" class="yummy apple">Mutsu</li>
      <li id="mcintosh" class="yummy">McIntosh</li>
      <li></li>
    </ul>
    

    And the associated JavaScript:

    $('golden-delicious').inspect();
    // -> '<li id="golden-delicious">'
    
    $('mutsu').inspect();
    // -> '<li id="mutsu" class="yummy apple">'
    
    $('mutsu').next().inspect();
    // -> '<li>'

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#makeClipping

    Simulates the poorly-supported CSS clip property by setting element's overflow value to hidden.

    To undo clipping, use Element.undoClipping.

    The visible area is determined by element's width and height.

    Example
    language:html
    <div id="framer">
      <img src="/assets/2007/1/14/chairs.jpg" alt="example" />
    </div>
    

    Then:

    $('framer').makeClipping().setStyle({width: '100px', height: '100px'});
    // -> Element
    

    Another example:

    language: html
    <a id="clipper" href="#">Click me to try it out.</a>
    
    <div id="framer">
      <img src="/assets/2007/2/24/chairs.jpg" alt="example" />
    </div>
    
    <script type="text/javascript" charset="utf-8">
      var Example = {
        clip: function(){
          $('clipper').update('undo clipping!');
          $('framer').makeClipping().setStyle({width: '100px', height: '100px'});
        },
        unClip: function(){
          $('clipper').update('clip!');
          $('framer').undoClipping();
        },
        toggleClip: function(event){
          if($('clipper').innerHTML == 'undo clipping!') Example.unClip();
          else Example.clip();
          Event.stop(event);
        }
      };
      Event.observe('clipper', 'click', Example.toggleClip);
    </script>

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#makePositioned

    Allows for the easy creation of a CSS containing block by setting element's CSS position to relative if its initial position is either static or undefined.

    To revert back to element's original CSS position, use Element.undoPositioned.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#match

      • Element#match(selector)
        • boolean
      • selector
        • String
      • A CSS selector.

    Checks if element matches the given CSS selector.

    Examples
    language: html
    <ul id="fruits">
      <li id="apples">
        <ul>
          <li id="golden-delicious">Golden Delicious</li>
          <li id="mutsu" class="yummy">Mutsu</li>
          <li id="mcintosh" class="yummy">McIntosh</li>
          <li id="ida-red">Ida Red</li>
        </ul>
      </li>
    </ul>
    

    Then:

    $('fruits').match('ul');
    // -> true
    
    $('mcintosh').match('li#mcintosh.yummy');
    // -> true
    
    $('fruits').match('p');
    // -> false

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#measure

      • Element#measure(property)

    Gives the pixel value of element's dimension specified by property.

    Useful for one-off measurements of elements. If you find yourself calling this method frequently over short spans of code, you might want to call Element.getLayout and operate on the Element.Layout object itself (thereby taking advantage of measurement caching).

    Examples
    $('troz').measure('width'); //-> 150
    $('troz').measure('border-top'); //-> 5
    $('troz').measure('top'); //-> 226
    
    Caveats
    • Element.measure can measure the dimensions of an element hidden with CSS (display: none), but only if its parent element is visible.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#next

      • Element#next
      • expression
        • String
      • A CSS selector.

    Returns element's first following sibling (or the Nth, if index is specified) that matches expression. If no expression is provided, all following siblings are considered. If none matches these criteria, undefined is returned.

    More information

    The Element.next method is part of Prototype's ultimate DOM traversal toolkit (check out Element.up, Element.down and Element.previous for some more Prototypish niceness). It allows precise index-based and/or CSS expression-based selection of any of element's following siblings. (Note that two elements are considered siblings if they have the same parent, so for example, the head and body elements are siblings—their parent is the html element.)

    As it totally ignores text nodes (it only returns elements), you don't have to worry about whitespace nodes.

    And as an added bonus, all elements returned are already extended (see Element.extend) allowing chaining:

    $(element).down(1).next('li', 2).hide();
    

    Walking the DOM has never been that easy!

    Arguments

    If no arguments are passed, element's following sibling is returned (this is similar as calling nextSibling except Element.next returns an already extended element).

    If index is defined, element's corresponding following sibling is returned. (This is equivalent to selecting an element from the array of elements returned by the method Element.nextSiblings). Note that the sibling right below element has an index of 0.

    If expression is defined, Element.next will return the element first following sibling that matches it.

    If both expression and index are defined, Element.next will collect all of element's following siblings matching the given CSS expression and will return the one at the specified index.

    In all of the above cases, if no following sibling is found, undefined will be returned.

    Examples
    language: html
    <ul id="fruits">
      <li id="apples">
        <h3 id="title">Apples</h3>
        <ul id="list-of-apples">
          <li id="golden-delicious">Golden Delicious</li>
          <li id="mutsu">Mutsu</li>
          <li id="mcintosh" class="yummy">McIntosh</li>
          <li id="ida-red" class="yummy">Ida Red</li>
        </ul>
        <p id="saying">An apple a day keeps the doctor away.</p>  
      </li>
    </ul>
    

    Get the first sibling after "#title":

    $('title').next();
    // or:
    $('title').next(0);
    // -> ul#list-of-apples
    

    Get the second sibling after "#title":

    $('title').next(1);
    // -> p#saying
    

    Get the first sibling after "#title" with node name "p":

    $('title').next('p');
    // -> p#sayings
    

    Get the first sibling after "#golden-delicious" with class name "yummy":

    $('golden-delicious').next('.yummy');
    // -> li#mcintosh
    

    Get the second sibling after "#golden-delicious" with class name "yummy":

    $('golden-delicious').next('.yummy', 1);
    // -> li#ida-red
    

    Try to get the first sibling after "#ida-red":

    $('ida-red').next();
    // -> undefined   

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#nextSiblings

      • Element#nextSiblings()

    Collects all of element's next siblings and returns them as an Array of elements.

    Two elements are siblings if they have the same parent. So for example, the head and body elements are siblings (their parent is the html element). Next-siblings are simply the ones which follow element in the document.

    The returned Array reflects the siblings order in the document (e.g. an index of 0 refers to the sibling right below element).

    Note that all of Prototype's DOM traversal methods ignore text nodes and return element nodes only.

    Examples
    language: html
    <ul>
      <li id="golden-delicious">Golden Delicious</li>
      <li id="mutsu">Mutsu</li>
      <li id="mcintosh">McIntosh</li>
      <li id="ida-red">Ida Red</li>
    </ul>
    

    Then:

    $('mutsu').nextSiblings();
    // -> [li#mcintosh, li#ida-red]
    
    $('ida-red').nextSiblings();
    // -> []

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#observe

      • Element#observe(eventName, handler)

    See Event.observe.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#on

      • Element#on(eventName[, selector], callback)

    See Event.on.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#positionedOffset

      • Element#positionedOffset()

    Returns element's offset relative to its closest positioned ancestor (the element that would be returned by Element.getOffsetParent).

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#previous

      • Element#previous
      • Element#previous([index = 0])
      • expression
        • String
      • A CSS selector.

    Returns element's first previous sibling (or the Nth, if index is specified) that matches expression. If no expression is provided, all previous siblings are considered. If none matches these criteria, undefined is returned.

    More information

    The Element.previous method is part of Prototype's ultimate DOM traversal toolkit (check out Element.up, Element.down and Element.next for some more Prototypish niceness). It allows precise index-based and/or CSS expression-based selection of any of element's previous siblings. (Note that two elements are considered siblings if they have the same parent, so for example, the head and body elements are siblings—their parent is the html element.)

    As it totally ignores text nodes (it only returns elements), you don't have to worry about whitespace nodes.

    And as an added bonus, all elements returned are already extended (see Element.extend) allowing chaining:

    $(element).down('p').previous('ul', 2).hide();
    

    Walking the DOM has never been that easy!

    Arguments

    If no arguments are passed, element's previous sibling is returned (this is similar as calling previousSibling except Element.previous returns an already extended element).

    If index is defined, element's corresponding previous sibling is returned. (This is equivalent to selecting an element from the array of elements returned by the method Element.previousSiblings). Note that the sibling right above element has an index of 0.

    If expression is defined, Element.previous will return the element first previous sibling that matches it.

    If both expression and index are defined, Element.previous will collect all of element's previous siblings matching the given CSS expression and will return the one at the specified index.

    In all of the above cases, if no previous sibling is found, undefined will be returned.

    Examples
    language: html
    <ul id="fruits">
      <li id="apples">
        <h3>Apples</h3>
        <ul id="list-of-apples">
          <li id="golden-delicious" class="yummy">Golden Delicious</li>
          <li id="mutsu" class="yummy">Mutsu</li>
          <li id="mcintosh">McIntosh</li>
          <li id="ida-red">Ida Red</li>
        </ul>
        <p id="saying">An apple a day keeps the doctor away.</p>  
      </li>
    </ul>
    

    Get the first previous sibling of "#saying":

    $('saying').previous();
    // or:
    $('saying').previous(0);
    // -> ul#list-of-apples
    

    Get the second previous sibling of "#saying":

    $('saying').previous(1);
    // -> h3
    

    Get the first previous sibling of "#saying" with node name "h3":

    $('saying').previous('h3');
    // -> h3
    

    Get the first previous sibling of "#ida-red" with class name "yummy":

    $('ida-red').previous('.yummy');
    // -> li#mutsu
    

    Get the second previous sibling of "#ida-red" with class name "yummy":

    $('ida-red').previous('.yummy', 1);
    // -> li#golden-delicious
    

    Try to get the sixth previous sibling of "#ida-red":

    $('ida-red').previous(5);
    // -> undefined

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#previousSiblings

      • Element#previousSiblings()

    Collects all of element's previous siblings and returns them as an Array of elements.

    Two elements are siblings if they have the same parent. So for example, the <head> and <body> elements are siblings (their parent is the <html> element). Previous-siblings are simply the ones which precede element in the document.

    The returned Array reflects the siblings inversed order in the document (e.g. an index of 0 refers to the lowest sibling i.e., the one closest to element).

    Note that all of Prototype's DOM traversal methods ignore text nodes and return element nodes only.

    Examples
    language: html
    <ul>
      <li id="golden-delicious">Golden Delicious</li>
      <li id="mutsu">Mutsu</li>
      <li id="mcintosh">McIntosh</li>
      <li id="ida-red">Ida Red</li>
    </ul>
    

    Then:

    $('mcintosh').previousSiblings();
    // -> [li#mutsu, li#golden-delicious]
    
    $('golden-delicious').previousSiblings();
    // -> []

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#purge

      • Element#purge()
        • null

    Removes all event listeners and storage keys from an element.

    To be used just before removing an element from the page.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#readAttribute

      • Element#readAttribute(attributeName)

    Returns the value of element's attribute or null if attribute has not been specified.

    This method serves two purposes. First it acts as a simple wrapper around getAttribute which isn't a "real" function in Safari and Internet Explorer (it doesn't have .apply or .call for instance). Secondly, it cleans up the horrible mess Internet Explorer makes when handling attributes.

    Examples
    language: html
    <a id="tag" href="/tags/prototype" rel="tag" title="view related bookmarks." my_widget="some info.">Prototype</a>
    

    Then:

    $('tag').readAttribute('href');
    // -> '/tags/prototype'
    
    $('tag').readAttribute('title');
    // -> 'view related bookmarks.'
    
    $('tag').readAttribute('my_widget');
    // -> 'some info.'

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#recursivelyCollect

      • Element#recursivelyCollect(property)

    Recursively collects elements whose relationship to element is specified by property. property has to be a property (a method won't do!) of element that points to a single DOM node (e.g., nextSibling or parentNode).

    More information

    This method is used internally by Element.ancestors, Element.descendants, Element.nextSiblings, Element.previousSiblings and Element.siblings which offer really convenient way to grab elements, so directly accessing Element.recursivelyCollect should seldom be needed. However, if you are after something out of the ordinary, it is the way to go.

    Note that all of Prototype's DOM traversal methods ignore text nodes and return element nodes only.

    Examples
    language: html
    <ul id="fruits">
      <li id="apples">
        <ul id="list-of-apples">
          <li id="golden-delicious"><p>Golden Delicious</p></li>
          <li id="mutsu">Mutsu</li>
          <li id="mcintosh">McIntosh</li>
          <li id="ida-red">Ida Red</li>
        </ul>
      </li>
    </ul>
    

    And the associated JavaScript:

    $('fruits').recursivelyCollect('firstChild');
    // -> [li#apples, ul#list-of-apples, li#golden-delicious, p]

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#relativize

    Turns element into a relatively-positioned element without changing its position in the page layout.

    Used to undo a call to Element.absolutize.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#remove

    Completely removes element from the document and returns it.

    If you would rather just hide the element and keep it around for further use, try Element.hide instead.

    Examples
    language: html
    // Before:
    <ul>
      <li id="golden-delicious">Golden Delicious</li>
      <li id="mutsu">Mutsu</li>
      <li id="mcintosh">McIntosh</li>
      <li id="ida-red">Ida Red</li>
    </ul>
    

    And the associated JavaScript:

    $('mutsu').remove();
    // -> Element (and removes li#mutsu)
    

    The resulting HTML:

    language: html
    <ul>
      <li id="golden-delicious">Golden Delicious</li>
      <li id="mcintosh">McIntosh</li>
      <li id="ida-red">Ida Red</li>
    </ul>

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#removeClassName

      • Element#removeClassName(className)

    Removes CSS class className from element.

    Examples

    Assuming this HTML:

    language: html
    <div id="mutsu" class="apple fruit food"></div>
    

    Then:

    $('mutsu').removeClassName('food');
    // -> Element
    
    $('mutsu').classNames;
    // -> 'apple fruit'

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#replace

      • Element#replace([newContent])

    Replaces element itself with newContent and returns element.

    Keep in mind that this method returns the element that has just been removed — not the element that took its place.

    newContent can be either plain text, an HTML snippet or any JavaScript object which has a toString() method.

    If newContent contains any <script> tags, these will be evaluated after element has been replaced (Element.replace internally calls String#evalScripts).

    Note that if no argument is provided, Element.replace will simply clear element of its content. However, using Element.remove to do so is both faster and more standard compliant.

    Examples
    language: html
    <div id="food">
      <div id="fruits">
        <p id="first">Kiwi, banana <em>and</em> apple.</p>
      </div>
    </div>
    

    Passing an HTML snippet:

    $('first').replace('<ul id="favorite"><li>kiwi</li><li>banana</li><li>apple</li></ul>');
    // -> Element (p#first)
    
    $('fruits').innerHTML;
    // -> '<ul id="favorite"><li>kiwi</li><li>banana</li><li>apple</li></ul>'
    

    Again, with a <script> tag thrown in:

    $('favorite').replace('<p id="still-first">Melon, oranges <em>and</em> grapes.</p><script>alert("removed!")</script>');
    // -> Element (ul#favorite) and prints "removed!" in an alert dialog.
    
    $('fruits').innerHTML;
    // -> '<p id="still-first">Melon, oranges <em>and</em> grapes.</p>'
    

    With plain text:

    $('still-first').replace('Melon, oranges and grapes.');
    // -> Element (p#still-first)
    
    $('fruits').innerHTML;
    // -> 'Melon, oranges and grapes.'
    

    Finally, relying on the toString() method:

    $('fruits').replace(123);
    // -> Element
    
    $('food').innerHTML;
    // -> '123'
    
    Warning

    Using Element.replace as an instance method (e.g., $('foo').replace('<p>Bar</p>')) causes errors in Opera 9 when used on input elements. The replace property is reserved on input elements as part of Web Forms 2. As a workaround, use the generic version instead (Element.replace('foo', '<p>Bar</p>')).

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#retrieve

      • Element#retrieve(key[, defaultValue])
        • ?

    Retrieves custom metadata set on element with Element.store.

    If the value is undefined and defaultValue is given, it will be stored on the element as its new value for that key, then returned.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#scrollTo

    Scrolls the window so that element appears at the top of the viewport.

    This has a similar effect than what would be achieved using HTML anchors (except the browser's history is not modified).

    Example
    $(element).scrollTo();
    // -> Element

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#select

      • Element#select(expression...)
      • expression
        • String
      • A CSS selector.

    Takes an arbitrary number of CSS selectors and returns an array of descendants of element that match any of them.

    This method is very similar to $$ but can be used within the context of one element, rather than the whole document. The supported CSS syntax is identical, so please refer to the $$ docs for details.

    Examples
    language: html
    <ul id="fruits">
      <li id="apples">
        <h3 title="yummy!">Apples</h3>
        <ul id="list-of-apples">
          <li id="golden-delicious" title="yummy!" >Golden Delicious</li>
          <li id="mutsu" title="yummy!">Mutsu</li>
          <li id="mcintosh">McIntosh</li>
          <li id="ida-red">Ida Red</li>
        </ul>
        <p id="saying">An apple a day keeps the doctor away.</p>  
      </li>
    </ul>
    

    Then:

    $('apples').select('[title="yummy!"]');
    // -> [h3, li#golden-delicious, li#mutsu]
    
    $('apples').select( 'p#saying', 'li[title="yummy!"]');
    // -> [li#golden-delicious, li#mutsu,  p#saying]
    
    $('apples').select('[title="disgusting!"]');
    // -> []
    
    Tip

    Element.select can be used as a pleasant alternative to the native method getElementsByTagName:

    var nodes  = $A(someUL.getElementsByTagName('li')).map(Element.extend);
    var nodes2 = someUL.select('li');
    

    In the first example, you must explicitly convert the result set to an Array (so that Prototype's Enumerable methods can be used) and must manually call Element.extend on each node (so that custom instance methods can be used on the nodes). Element.select takes care of both concerns on its own.

    If you're using 1.6 or above (and the performance optimizations therein), the speed difference between these two examples is negligible.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#setOpacity

      • Element#setOpacity(opacity)

    Sets the visual opacity of an element while working around inconsistencies in various browsers. The opacity argument should be a floating point number, where the value of 0 is fully transparent and 1 is fully opaque.

    Element.setStyle method uses Element.setOpacity internally when needed.

    Examples
    var element = $('myelement');
    // set to 50% transparency
    element.setOpacity(0.5);
    
    // these are equivalent, but allow for setting more than
    // one CSS property at once:
    element.setStyle({ opacity: 0.5 });
    element.setStyle("opacity: 0.5");

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#setStyle

    Modifies element's CSS style properties. Styles are passed as a hash of property-value pairs in which the properties are specified in their camelized form.

    Examples
    $(element).setStyle({
      backgroundColor: '#900',
      fontSize: '12px'
    });
    // -> Element
    
    Notes

    The method transparently deals with browser inconsistencies for float (however, as float is a reserved keyword, you must either escape it or use cssFloat instead) and opacity (which accepts values between 0 -fully transparent- and 1 -fully opaque-). You can safely use either of the following across all browsers:

    $(element).setStyle({
      cssFloat: 'left',
      opacity: 0.5
    });
    // -> Element
    
    $(element).setStyle({
      'float': 'left', // notice how float is surrounded by single quotes
      opacity: 0.5
    });
    // -> Element
    

    Not all CSS shorthand properties are supported. You may only use the CSS properties described in the Document Object Model (DOM) Level 2 Style Specification.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#show

    Removes display: none on element. Returns element.

    Examples

    Show a single element:

    <div id="error-message" style="display:none;"></div>
    
    $('error-message').show();
    // -> Element (and displays div#error-message)
    

    Show multiple elements using Enumerable#each:

    ['content', 'navigation', 'footer'].each(Element.show);
    // -> ['content', 'navigation', 'footer'] 
    

    Show multiple elements using Enumerable#invoke:

    $('content', 'navigation', 'footer').invoke('show');
    // -> [Element, Element, Element]
    
    Notes

    Element.show cannot display elements hidden via CSS stylesheets. Note that this is not a Prototype limitation but a consequence of how the CSS display property works.

    <style>
      #hidden-by-css {
        display: none;
      }
    </style>
    
    [...]
    
    <div id="hidden-by-css"></div>
    
    $('hidden-by-css').show(); // DOES NOT WORK!
    // -> Element (div#error-message is still hidden!)

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#siblings

    Collects all of element's siblings and returns them as an Array of elements.

    Two elements are siblings if they have the same parent. So for example, the head and body elements are siblings (their parent is the html element).

    The returned Array reflects the siblings' order in the document (e.g. an index of 0 refers to element's topmost sibling).

    Note that all of Prototype's DOM traversal methods ignore text nodes and return element nodes only.

    Examples
    language: html
    <ul>
      <li id="golden-delicious">Golden Delicious</li>
      <li id="mutsu">Mutsu</li>
      <li id="mcintosh">McIntosh</li>
      <li id="ida-red">Ida Red</li>
    </ul>
    

    Then:

    $('mutsu').siblings();
    // -> [li#golden-delicious, li#mcintosh, li#ida-red]

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#stopObserving

      • Element#stopObserving([eventName][, handler])

    See Event.stopObserving.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#store

    Stores a key/value pair of custom metadata on the element.

    The metadata can later be retrieved with Element.retrieve.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#toggle

    Toggles the CSS display of element. Returns element.

    Switches an element's CSS display between none and its inherited value (usually block or inline).

    By default, toggle will switch the display to the opposite of its current state, but will use the bool argument instead if it's provided (true to show the element, false to hide it).

    Examples
    <div id="welcome-message"></div>
    <div id="error-message" style="display:none;"></div>
    
    $('welcome-message').toggle();
    // -> Element (and hides div#welcome-message)
    
    $('error-message').toggle();
    // -> Element (and displays div#error-message)
    
    $('error-message).toggle(true);
    // -> Element (and displays div#error-message, no matter what its
    //    previous state)
    

    Toggle multiple elements using Enumerable#each:

    ['error-message', 'welcome-message'].each(Element.toggle);
    // -> ['error-message', 'welcome-message'] 
    

    Toggle multiple elements using Enumerable#invoke:

    $('error-message', 'welcome-message').invoke('toggle');
    // -> [Element, Element]
    
    $('error-message', 'welcome-message').invoke('toggle', false);
    // -> [Element, Element] (and hides both elements, no matter what
          their previous state)
    
    Notes

    Element.toggle cannot display elements hidden via CSS stylesheets. Note that this is not a Prototype limitation but a consequence of how the CSS display property works.

    <style>
      #hidden-by-css {
        display: none;
      }
    </style>
    
    [...]
    
    <div id="hidden-by-css"></div>
    
    $('hidden-by-css').toggle(); // WON'T WORK!
    // -> Element (div#hidden-by-css is still hidden!)

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#toggleClassName

      • Element#toggleClassName(className[, bool])

    Toggles the presence of CSS class className on element.

    By default, toggleClassName will flip to the opposite state, but will use bool instead if it's given; true will add the class name and false will remove it.

    Examples
    language: html
    <div id="mutsu" class="apple"></div>
    

    Then:

    $('mutsu').hasClassName('fruit');
    // -> false
    
    $('mutsu').toggleClassName('fruit');
    // -> Element
    
    $('mutsu').hasClassName('fruit');
    // -> true
    
    $('mutsu').toggleClassName('fruit', true);
    // -> Element (keeps the "fruit" class name that was already there)

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#undoClipping

    Sets element's CSS overflow property back to the value it had before Element.makeClipping was applied.

    Example
    language: html
    <div id="framer">
      <img src="/assets/2007/1/14/chairs.jpg" alt="example" />
    </div>
    

    Then:

    $('framer').undoClipping();
    // -> Element (and sets the CSS overflow property to its original value).
    

    Another example:

    language: html
    <a id="clipper" href="#">Click me to try it out.</a>
    
    <div id="framer">
      <img src="/assets/2007/2/24/chairs_1.jpg" alt="example" />
    </div>
    
    <script type="text/javascript" charset="utf-8">
      var Example = {
        clip: function(){
          $('clipper').update('undo clipping!');
          $('framer').makeClipping().setStyle({width: '100px', height: '100px'});
        },
        unClip: function(){
          $('clipper').update('clip!');
          $('framer').undoClipping();
        },
        toggleClip: function(event){
          if($('clipper').innerHTML == 'clip!') Example.clip();
          else Example.unClip();
          Event.stop(event);
        }
      };
      $('framer').makeClipping().setStyle({width: '100px', height: '100px'});
      Event.observe('clipper', 'click', Example.toggleClip);
    </script>

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#undoPositioned

    Sets element back to the state it was in before Element.makePositioned was applied to it.

    element's absolutely positioned children will now have their positions set relatively to element's nearest ancestor with a CSS position of 'absolute', 'relative' or 'fixed'.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#up

      • Element#up
      • expression
        • String
      • A CSS selector.

    Returns element's first ancestor (or the Nth ancestor, if index is specified) that matches expression. If no expression is provided, all ancestors are considered. If no ancestor matches these criteria, undefined is returned.

    More information

    The Element.up method is part of Prototype's ultimate DOM traversal toolkit (check out Element.down, Element.next and Element.previous for some more Prototypish niceness). It allows precise index-based and/or CSS rule-based selection of any of element's ancestors.

    As it totally ignores text nodes (it only returns elements), you don't have to worry about whitespace nodes.

    And as an added bonus, all elements returned are already extended (see [[Element.extended]]) allowing chaining:

    $(element).up(1).next('li', 2).hide();
    

    Walking the DOM has never been that easy!

    Arguments

    If no arguments are passed, element's first ancestor is returned (this is similar to calling parentNode except Element.up returns an already extended element.

    If index is defined, element's corresponding ancestor is returned. (This is equivalent to selecting an element from the array of elements returned by the method Element.ancestors). Note that the first element has an index of 0.

    If expression is defined, Element.up will return the first ancestor that matches it.

    If both expression and index are defined, Element.up will collect all the ancestors matching the given CSS expression and will return the one at the specified index.

    In all of the above cases, if no descendant is found, undefined will be returned.

    Examples

    language: html
    <html>
      [...]
      <body>
        <ul id="fruits">
          <li id="apples" class="keeps-the-doctor-away">
            <ul>
              <li id="golden-delicious">Golden Delicious</li>
              <li id="mutsu" class="yummy">Mutsu</li>
              <li id="mcintosh" class="yummy">McIntosh</li>
              <li id="ida-red">Ida Red</li>
            </ul>
          </li>
        </ul>
      </body>
    </html>
    

    Get the first ancestor of "#fruites":

    $('fruits').up();
    // or:
    $('fruits').up(0);
    // -> body
    

    Get the third ancestor of "#mutsu":

    $('mutsu').up(2);
    // -> ul#fruits
    

    Get the first ancestor of "#mutsu" with the node name "li":

    $('mutsu').up('li');
    // -> li#apples
    

    Get the first ancestor of "#mutsu" with the class name "keeps-the-doctor-away":

    $('mutsu').up('.keeps-the-doctor-away');
    // -> li#apples
    

    Get the second ancestor of "#mutsu" with the node name "ul":

    $('mutsu').up('ul', 1);
    // -> ul#fruits
    

    Try to get the first ancestor of "#mutsu" with the node name "div":

    $('mutsu').up('div');
    // -> undefined

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#update

      • Element#update([newContent])

    Replaces the content of element with the newContent argument and returns element.

    newContent may be in any of these forms:

    • String: A string of HTML to be parsed and rendered
    • Element: An Element instance to insert
    • ...any object with a toElement method: The method is called and the resulting element used
    • ...any object with a toHTML method: The method is called and the resulting HTML string is parsed and rendered

    If newContent is omitted, the element's content is blanked out (i.e., replaced with an empty string).

    If newContent is a string and contains one or more inline <script> tags, the scripts are scheduled to be evaluated after a very brief pause (using Function#defer) to allow the browser to finish updating the DOM. Note that the scripts are evaluated in the scope of String#evalScripts, not in the global scope, which has important ramifications for your vars and functions. See String#evalScripts for details.

    Note that this method allows seamless content update of table related elements in Internet Explorer 6 and beyond.

    Any nodes replaced with Element.update will first have event listeners unregistered and storage keys removed. This frees up memory and prevents leaks in certain versions of Internet Explorer. (See Element.purge).

    Examples
    language: html
    <div id="fruits">carrot, eggplant and cucumber</div>
    

    Passing a regular string:

    $('fruits').update('kiwi, banana and apple');
    // -> Element
    $('fruits').innerHTML;
    // -> 'kiwi, banana and apple'
    

    Clearing the element's content:

    $('fruits').update();
    // -> Element
    $('fruits').innerHTML;
    // -> '' (an empty string)
    

    And now inserting an HTML snippet:

    $('fruits').update('<p>Kiwi, banana <em>and</em> apple.</p>');
    // -> Element
    $('fruits').innerHTML;
    // -> '<p>Kiwi, banana <em>and</em> apple.</p>'
    

    ... with a <script> tag thrown in:

    $('fruits').update('<p>Kiwi, banana <em>and</em> apple.</p><script>alert("updated!")</script>');
    // -> Element (and prints "updated!" in an alert dialog).
    $('fruits').innerHTML;
    // -> '<p>Kiwi, banana <em>and</em> apple.</p>'
    

    Relying on the toString() method:

    $('fruits').update(123);
    // -> Element
    $('fruits').innerHTML;
    // -> '123'
    

    Finally, you can do some pretty funky stuff by defining your own toString() method on your custom objects:

    var Fruit = Class.create({
      initialize: function(fruit){
        this.fruit = fruit;
      },
      toString: function(){
        return 'I am a fruit and my name is "' + this.fruit + '".'; 
      }
    });
    var apple = new Fruit('apple');
    
    $('fruits').update(apple);
    $('fruits').innerHTML;
    // -> 'I am a fruit and my name is "apple".'

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#viewportOffset

      • Element#viewportOffset()

    Returns the X/Y coordinates of element relative to the viewport.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#visible

      • Element#visible()
        • Boolean

    Tells whether element is visible (i.e., whether its inline display CSS property is set to none.

    Examples
    language: html
    <div id="visible"></div>
    <div id="hidden" style="display: none;"></div>
    

    And the associated JavaScript:

    $('visible').visible();
    // -> true
    
    $('hidden').visible();
    // -> false
    
    Notes

    Styles applied via a CSS stylesheet are not taken into consideration. Note that this is not a Prototype limitation, it is a CSS limitation.

    language: html
    <style>
      #hidden-by-css {
        display: none;
      }
    </style>
    
    [...]
    
    <div id="hidden-by-css"></div>
    

    And the associated JavaScript:

    $('hidden-by-css').visible();
    // -> true

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#wrap

      • Element#wrap(wrapper[, attributes])
      • wrapper
        • Element
        • String
      • An element to wrap element inside, or else a string representing the tag name of an element to be created.

      • attributes
        • Object
      • A set of attributes to apply to the wrapper element. Refer to the Element constructor for usage.

    Wraps an element inside another, then returns the wrapper.

    If the given element exists on the page, Element.wrap will wrap it in place — its position will remain the same.

    The wrapper argument can be either an existing Element or a string representing the tag name of an element to be created. The optional attributes argument can contain a list of attribute/value pairs that will be set on the wrapper using Element.writeAttribute.

    Examples

    Original HTML:

    language: html
    <table id="data">
      <tr>
        <th>Foo</th>
        <th>Bar</th>
      </tr>
      <tr>
        <td>1</td>
        <td>2</td>
      </tr>
    </table>
    

    JavaScript:

    // approach 1:
    var div = new Element('div', { 'class': 'table-wrapper' });
    $('data').wrap(div);
    
    // approach 2:
    $('data').wrap('div', { 'class': 'table-wrapper' });
    
    // Both examples are equivalent &mdash; they return the DIV.
    

    Resulting HTML:

    language: html
    <div class="table-wrapper">
      <table id="data">
        <tr>
          <th>Foo</th>
          <th>Bar</th>
        </tr>
        <tr>
          <td>1</td>
          <td>2</td>
        </tr>
      </table>
    </div> 
    
    Warning

    Using Element.wrap as an instance method (e.g., $('foo').wrap('p')) causes errors in Internet Explorer when used on textarea elements. The wrap property is reserved on textarea's as a proprietary extension to HTML. As a workaround, use the generic version instead (Element.wrap('foo', 'p')).

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Element#writeAttribute

      • Element#writeAttribute
      • Element#writeAttribute(attributes)

    Adds, specifies or removes attributes passed as either a hash or a name/value pair.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Event

    Description

    The namespace for Prototype's event system.

    Events: a fine mess

    Event management is one of the really sore spots of cross-browser scripting.

    True, the prevalent issue is: everybody does it the W3C way, and MSIE does it another way altogether. But there are quite a few subtler, sneakier issues here and there waiting to bite your ankle — such as the keypress/keydown issue with KHTML-based browsers (Konqueror and Safari). Also, MSIE has a tendency to leak memory when it comes to discarding event handlers.

    Prototype to the rescue

    Of course, Prototype smooths it over so well you'll forget these troubles even exist. Enter the Event namespace. It is replete with methods that help to normalize the information reported by events across browsers.

    Event also provides a standardized list of key codes you can use with keyboard-related events, including KEY_BACKSPACE, KEY_TAB, KEY_RETURN, KEY_ESC, KEY_LEFT, KEY_UP, KEY_RIGHT, KEY_DOWN, KEY_DELETE, KEY_HOME, KEY_END, KEY_PAGEUP, KEY_PAGEDOWN and KEY_INSERT.

    The functions you're most likely to use a lot are Event.observe, Event.element and Event.stop. If your web app uses custom events, you'll also get a lot of mileage out of Event.fire.

    Instance methods on event objects

    As of Prototype 1.6, all methods on the Event object are now also available as instance methods on the event object itself:

    Before

    $('foo').observe('click', respondToClick);
    
    function respondToClick(event) {
      var element = Event.element(event);
      element.addClassName('active');
    }
    

    After

    $('foo').observe('click', respondToClick);
    
    function respondToClick(event) {
      var element = event.element();
      element.addClassName('active');
    }
    

    These methods are added to the event object through Event.extend, in the same way that Element methods are added to DOM nodes through Element.extend. Events are extended automatically when handlers are registered with Prototype's Event.observe method; if you're using a different method of event registration, for whatever reason,you'll need to extend these events manually with Event.extend.

    Classes

    • Event.Handler

      Creates an observer on an element that listens for a particular event on that element's descendants, optionally filtering by a CSS selector.

    Event.Handler

    Description

    Creates an observer on an element that listens for a particular event on that element's descendants, optionally filtering by a CSS selector.

    This class simplifies the common "event delegation" pattern, in which one avoids adding an observer to a number of individual elements and instead listens on a common ancestor element.

    For more information on usage, see Event.on.

    Instance properties

    Event.Handler.new

      • new Event.Handler(element, eventName[, selector], callback)
      • element
        • Element
      • The element to listen on.

      • eventName
        • String
      • An event to listen for. Can be a standard browser event or a custom event.

      • selector
        • String
      • A CSS selector. If specified, will call callback only when it can find an element that matches selector somewhere in the ancestor chain between the event's target element and the given element.

      • callback
        • Function
      • The event handler function. Should expect two arguments: the event object and the element that received the event. (If selector was given, this element will be the one that satisfies the criteria described just above; if not, it will be the one specified in the element argument).

    Instantiates an Event.Handler. Will not begin observing until Event.Handler#start is called.

    Event.Handler#start

    Starts listening for events. Returns itself.

    Event.Handler#stop

    Stops listening for events. Returns itself.

    Event.element

    Deprecated
      • event
        • Event
      • An Event object

    Returns the DOM element on which the event occurred. This method is deprecated, use Event.findElement instead.

    Example

    Here's a simple bit of code which hides any paragraph when directly clicked.

    document.observe('click', function(event) {
      var element = Event.element(event);
      if ('P' == element.tagName)
        element.hide();
    });
    
    See also

    There is a subtle distinction between this function and Event.findElement.

    Note for Prototype 1.5.0

    Note that prior to version 1.5.1, if the browser does not support native DOM extensions (see the Element section for further details), the element returned by Event.element might very well not be extended. If you intend to use methods from Element.Methods on it, you need to wrap the call in the $ function like so:

    document.observe('click', function(event) {
      var element = $(Event.element(event));
      // ...
    });

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Event.extend

      • event
        • Event
      • An Event object

    Extends event with all of the methods contained in Event.Methods.

    Note that all events inside handlers that were registered using Event.observe or Element.observe will be extended automatically.

    You need only call Event.extend manually if you register a handler a different way (e.g., the onclick attribute). We really can't encourage that sort of thing, though.

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Event.findElement

      • Event.findElement(event[, expression])
      • event
        • Event
      • An Event object

      • expression
        • String
      • An optional CSS selector

    Returns the first DOM element that matches a given CSS selector — starting with the element on which the event occurred, then moving up its ancestor chain. If expression is not given, the element which fired the event is returned.

    If no matching element is found, the document itself (HTMLDocument node) is returned.

    Example

    Here's a simple example that lets you click everywhere on the page and hides the closest-fitting paragraph around your click (if any).

    document.observe('click', function(event) {
      var element = event.findElement('p');
      if (element != document)
        $(element).hide();
    });

    This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

    Event.fire

      • Event.fire(element, eventName[, memo][, bubble = true])
      • memo
        • Metadata for the event. Will be accessible to event handlers through the event's memo property.

        • bubble
          • Boolean
        • Whether the event should bubble.

      Fires a custom event of name eventName with element as its target.

      Custom events must include a colon (:) in their names.

      Event.isLeftClick

        • Event.isLeftClick(event)
          • Boolean
        • event
          • Event
        • An Event object

      Determines whether a button-related mouse event involved the left mouse button.

      Keep in mind that the "left" mouse button is actually the "primary" mouse button. When a mouse is in left-handed mode, the browser will report clicks of the right button as "left-clicks."

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Event.isMiddleClick

        • Event.isMiddleClick(event)
          • Boolean
        • event
          • Event
        • An Event object

      Determines whether a button-related mouse event involved the middle mouse button.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Event.isRightClick

        • Event.isRightClick(event)
          • Boolean
        • event
          • Event
        • An Event object

      Determines whether a button-related mouse event involved the right mouse button.

      Keep in mind that the "right" mouse button is actually the "secondary" mouse button. When a mouse is in left-handed mode, the browser will report clicks of the left button as "left-clicks."

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Event.observe

        • Event.observe(element, eventName, handler)
        • element
          • Element
          • String
        • The DOM element to observe, or its ID.

        • eventName
          • String
        • The name of the event, in all lower case, without the "on" prefix — e.g., "click" (not "onclick").

        • handler
          • Function
        • The function to call when the event occurs.

      Registers an event handler on a DOM element. Aliased as Element#observe.

      Event.observe smooths out a variety of differences between browsers and provides some handy additional features as well. Key features in brief:

      • Several handlers can be registered for the same event on the same element.
      • Prototype figures out whether to use addEventListener (W3C standard) or attachEvent (MSIE); you don't have to worry about it.
      • The handler is passed an extended Event object (even on MSIE).
      • The handler's context (this value) is set to the extended element being observed (even if the event actually occurred on a descendent element and bubbled up).
      • Prototype handles cleaning up the handler when leaving the page (important for MSIE memory leak prevention).
      • Event.observe makes it possible to stop observing the event easily via Event.stopObserving.
      • Adds support for mouseenter / mouseleave events in all browsers.

      Although you can use Event.observe directly and there are times when that's the most convenient or direct way, it's more common to use its alias Element#observe. These two statements have the same effect:

      Event.observe('foo', 'click', myHandler);
      $('foo').observe('click', myHandler);
      

      The examples in this documentation use the Element#observe form.

      The Handler

      Signature:

      function handler(event) {
        // `this` = the element being observed
      }
      

      So for example, this will turn the background of the element 'foo' blue when it's clicked:

      $('foo').observe('click', function(event) {
        this.setStyle({backgroundColor: 'blue'});
      });
      

      Note that we used this to refer to the element, and that we received the event object as a parameter (even on MSIE).

      It's All About Timing

      One of the most common errors trying to observe events is trying to do it before the element exists in the DOM. Don't try to observe elements until after the document.observe event or window load event has been fired.

      Preventing the Default Event Action and Bubbling

      If we want to stop the event (e.g., prevent its default action and stop it bubbling), we can do so with the extended event object's Event#stop method:

      $('foo').observe('click', function(event) {
        event.stop();
      });
      
      Finding the Element Where the Event Occurred

      Since most events bubble from descendant elements up through the hierarchy until they're handled, we can observe an event on a container rather than individual elements within the container. This is sometimes called "event delegation". It's particularly handy for tables:

      language: html
      <table id='records'>
        <thead>
          <tr><th colspan='2'>No record clicked</th></tr>
        </thead>
        <tbody>
          <tr data-recnum='1'><td>1</td><td>First record</td></tr>
          <tr data-recnum='2'><td>2</td><td>Second record</td></tr>
          <tr data-recnum='3'><td>3</td><td>Third record</td></tr>
        </tbody>
      </table>
      

      Instead of observing each cell or row, we can simply observe the table:

      $('records').observe('click', function(event) {
        var clickedRow = event.findElement('tr');
        if (clickedRow) {
          this.down('th').update("You clicked record #" + clickedRow.readAttribute("data-recnum"));
        }
      });
      

      When any row in the table is clicked, we update the table's first header cell saying which record was clicked. Event#findElement finds the row that was clicked, and this refers to the table we were observing.

      Stopping Observing the Event

      If we don't need to observe the event anymore, we can stop observing it with Event.stopObserving or its Element#stopObserving alias.

      Using an Instance Method as a Handler

      If we want to use an instance method as a handler, we will probably want to use Function#bind to set the handler's context; otherwise, the context will be lost and this won't mean what we expect it to mean within the handler function. E.g.:

      var MyClass = Class.create({
        initialize: function(name, element) {
          this.name = name;
          element = $(element);
          if (element) {
            element.observe(this.handleClick.bind(this));
          }
        },
        handleClick: function(event) {
          alert("My name is " + this.name);
        },
      });
      

      Without the Function#bind, when handleClick was triggered by the event, this wouldn't refer to the instance and so the alert wouldn't show the name. Because we used Function#bind, it works correctly. See Function#bind for details. There's also Function#bindAsEventListener, which is handy for certain very specific situations. (Normally, Function#bind is all you need.)

      Side Notes

      Although Prototype smooths out most of the differences between browsers, the fundamental behavior of a browser implementation isn't changed. For example, the timing of the change or blur events varies a bit from browser to browser.

      Changes in 1.6.x

      Prior to Prototype 1.6, Event.observe supported a fourth argument (useCapture), a boolean that indicated whether to use the browser's capturing phase or its bubbling phase. Since MSIE does not support the capturing phase, we removed this argument from 1.6, lest it give users the false impression that they can use the capturing phase in all browsers.

      1.6 also introduced setting the this context to the element being observed, automatically extending the Event object, and the Event#findElement method.

      Event.on

        • Event.on(element, eventName[, selector], callback)
        • element
          • Element
          • String
        • The DOM element to observe, or its ID.

        • eventName
          • String
        • The name of the event, in all lower case, without the "on" prefix — e.g., "click" (not "onclick").

        • selector
          • String
        • A CSS selector. If specified, will call callback only when it can find an element that matches selector somewhere in the ancestor chain between the event's target element and the given element.

        • callback
          • Function
        • The event handler function. Should expect two arguments: the event object and the element that received the event. (If selector was given, this element will be the one that satisfies the criteria described just above; if not, it will be the one specified in the element argument). This function is always bound to element.

      Listens for events on an element's descendants, optionally filtering to match a given CSS selector.

      Creates an instance of Event.Handler, calls Event.Handler#start, then returns that instance. Keep a reference to this returned instance if you later want to unregister the observer.

      Usage

      Event.on can be used to set up event handlers with or without event delegation. In its simplest form, it works just like Event.observe:

      $("messages").on("click", function(event) {
        // ...
      });
      

      An optional second argument lets you specify a CSS selector for event delegation. This encapsulates the pattern of using Event#findElement to retrieve the first ancestor element matching a specific selector.

      $("messages").on("click", "a.comment", function(event, element) {
         // ...
      });
      

      Note the second argument in the handler above: it references the element matched by the selector (in this case, an a tag with a class of comment). This argument is important to use because within the callback, the this keyword will always refer to the original element (in this case, the element with the id of messages).

      Event.on differs from Event.observe in one other important way: its return value is an instance of Event.Handler. This instance has a stop method that will remove the event handler when invoked (and a start method that will attach the event handler again after it's been removed).

      // Register the handler:
      var handler = $("messages").on("click", "a.comment",
       this.click.bind(this));
      
      // Unregister the handler:
      handler.stop();
      
      // Re-register the handler:
      handler.start();
      

      This means that, unlike Event.stopObserving, there's no need to retain a reference to the handler function.

      Event.pointer

      Returns the absolute position of the pointer for a mouse event.

      Returns an object in the form { x: Number, y: Number}.

      Note that this position is absolute on the page, not on the viewport.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Event.pointerX

      Returns the absolute horizontal position of the pointer for a mouse event.

      Note that this position is absolute on the <body>, not on the viewport: scrolling right increases the returned value for events on the same viewport location.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Event.pointerY

      Returns the absolute vertical position of the pointer for a mouse event.

      Note that this position is absolute on the <body>, not on the viewport: scrolling down increases the returned value for events on the same viewport location.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Event.stop

        • Event.stop(event)
          • undefined

      Stops the event's propagation and prevents its eventual default action from being triggered.

      Stopping an event also sets a stopped property on that event for future inspection.

      There are two aspects to how your browser handles an event once it fires up:

      1. The browser usually triggers event handlers on the actual element the event occurred on, then on its parent element, and so on and so forth, until the document's root element is reached. This is called event bubbling, and is the most common form of event propagation. You may very well want to stop this propagation when you just handled an event, and don't want it to keep bubbling up (or see no need for it).

      2. Once your code had a chance to process the event, the browser handles it as well, if that event has a default behavior. For instance, clicking on links navigates to them; submitting forms sends them over to the server side; hitting the Return key in a single-line form field submits it; etc. You may very well want to prevent this default behavior if you do your own handling.

      Because stopping one of those aspects means, in 99.9% of the cases, preventing the other one as well, Prototype bundles both in this stop function. Calling it on an event object, stops propagation and prevents the default behavior.

      Example

      Here's a simple script that prevents a form from being sent to the server side if certain field is empty.

      Event.observe('signinForm', 'submit', function(event) {
        var login = $F('login').strip();
        if ('' == login) {
          Event.stop(event);
          // Display the issue one way or another
        }
      });

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Event.stopObserving

        • Event.stopObserving(element[, eventName][, handler])
        • element
          • Element
          • String
        • The element to stop observing, or its ID.

        • eventName
          • String
        • (Optional) The name of the event to stop observing, in all lower case, without the "on" — e.g., "click" (not "onclick").

        • handler
          • Function
        • (Optional) The handler to remove; must be the exact same reference that was passed to Event.observe.

      Unregisters one or more event handlers.

      If handler is omitted, unregisters all event handlers on element for that eventName. If eventName is also omitted, unregisters all event handlers on element. (In each case, only affects handlers registered via Prototype.)

      Examples

      Assuming:

      $('foo').observe('click', myHandler);
      

      ...we can stop observing using that handler like so:

      $('foo').stopObserving('click', myHandler);
      

      If we want to remove all 'click' handlers from 'foo', we leave off the handler argument:

      $('foo').stopObserving('click');
      

      If we want to remove all handlers for all events from 'foo' (perhaps we're about to remove it from the DOM), we simply omit both the handler and the event name:

      $('foo').stopObserving();
      
      A Common Error

      When using instance methods as observers, it's common to use Function#bind on them, e.g.:

      $('foo').observe('click', this.handlerMethod.bind(this));
      

      If you do that, this will not work to unregister the handler:

      $('foo').stopObserving('click', this.handlerMethod.bind(this)); // <== WRONG
      

      Function#bind returns a new function every time it's called, and so if you don't retain the reference you used when observing, you can't unhook that function specifically. (You can still unhook all handlers for an event, or all handlers on the element entirely.)

      To do this, you need to keep a reference to the bound function:

      this.boundHandlerMethod = this.handlerMethod.bind(this);
      $('foo').observe('click', this.boundHandlerMethod);
      

      ...and then to remove:

      $('foo').stopObserving('click', this.boundHandlerMethod); // <== Right

      Event#element

      Deprecated
        • event
          • Event
        • An Event object

      Returns the DOM element on which the event occurred. This method is deprecated, use Event.findElement instead.

      Example

      Here's a simple bit of code which hides any paragraph when directly clicked.

      document.observe('click', function(event) {
        var element = Event.element(event);
        if ('P' == element.tagName)
          element.hide();
      });
      
      See also

      There is a subtle distinction between this function and Event.findElement.

      Note for Prototype 1.5.0

      Note that prior to version 1.5.1, if the browser does not support native DOM extensions (see the Element section for further details), the element returned by Event.element might very well not be extended. If you intend to use methods from Element.Methods on it, you need to wrap the call in the $ function like so:

      document.observe('click', function(event) {
        var element = $(Event.element(event));
        // ...
      });

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Event#extend

        • event
          • Event
        • An Event object

      Extends event with all of the methods contained in Event.Methods.

      Note that all events inside handlers that were registered using Event.observe or Element.observe will be extended automatically.

      You need only call Event.extend manually if you register a handler a different way (e.g., the onclick attribute). We really can't encourage that sort of thing, though.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Event#findElement

        • Event#findElement([expression])
        • event
          • Event
        • An Event object

        • expression
          • String
        • An optional CSS selector

      Returns the first DOM element that matches a given CSS selector — starting with the element on which the event occurred, then moving up its ancestor chain. If expression is not given, the element which fired the event is returned.

      If no matching element is found, the document itself (HTMLDocument node) is returned.

      Example

      Here's a simple example that lets you click everywhere on the page and hides the closest-fitting paragraph around your click (if any).

      document.observe('click', function(event) {
        var element = event.findElement('p');
        if (element != document)
          $(element).hide();
      });

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Event#isLeftClick

        • Event#isLeftClick()
          • Boolean
        • event
          • Event
        • An Event object

      Determines whether a button-related mouse event involved the left mouse button.

      Keep in mind that the "left" mouse button is actually the "primary" mouse button. When a mouse is in left-handed mode, the browser will report clicks of the right button as "left-clicks."

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Event#isMiddleClick

        • Event#isMiddleClick()
          • Boolean
        • event
          • Event
        • An Event object

      Determines whether a button-related mouse event involved the middle mouse button.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Event#isRightClick

        • Event#isRightClick()
          • Boolean
        • event
          • Event
        • An Event object

      Determines whether a button-related mouse event involved the right mouse button.

      Keep in mind that the "right" mouse button is actually the "secondary" mouse button. When a mouse is in left-handed mode, the browser will report clicks of the left button as "left-clicks."

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Event#pointer

      Returns the absolute position of the pointer for a mouse event.

      Returns an object in the form { x: Number, y: Number}.

      Note that this position is absolute on the page, not on the viewport.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Event#pointerX

      Returns the absolute horizontal position of the pointer for a mouse event.

      Note that this position is absolute on the <body>, not on the viewport: scrolling right increases the returned value for events on the same viewport location.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Event#pointerY

      Returns the absolute vertical position of the pointer for a mouse event.

      Note that this position is absolute on the <body>, not on the viewport: scrolling down increases the returned value for events on the same viewport location.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Event#stop

        • Event#stop()
          • undefined

      Stops the event's propagation and prevents its eventual default action from being triggered.

      Stopping an event also sets a stopped property on that event for future inspection.

      There are two aspects to how your browser handles an event once it fires up:

      1. The browser usually triggers event handlers on the actual element the event occurred on, then on its parent element, and so on and so forth, until the document's root element is reached. This is called event bubbling, and is the most common form of event propagation. You may very well want to stop this propagation when you just handled an event, and don't want it to keep bubbling up (or see no need for it).

      2. Once your code had a chance to process the event, the browser handles it as well, if that event has a default behavior. For instance, clicking on links navigates to them; submitting forms sends them over to the server side; hitting the Return key in a single-line form field submits it; etc. You may very well want to prevent this default behavior if you do your own handling.

      Because stopping one of those aspects means, in 99.9% of the cases, preventing the other one as well, Prototype bundles both in this stop function. Calling it on an event object, stops propagation and prevents the default behavior.

      Example

      Here's a simple script that prevents a form from being sent to the server side if certain field is empty.

      Event.observe('signinForm', 'submit', function(event) {
        var login = $F('login').strip();
        if ('' == login) {
          Event.stop(event);
          // Display the issue one way or another
        }
      });

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form

      Description

      Utilities for dealing with forms in the DOM.

      Form is a namespace for all things form-related, packed with form manipulation and serialization goodness. While it holds methods dealing with forms as a whole, its submodule Form.Element deals with specific form controls.

      Many of these methods are also available directly on form elements.

      Namespaces

      • Form.Element

        Utilities for dealing with form controls in the DOM.

      Classes

      Form.Element

      Description

      Utilities for dealing with form controls in the DOM.

      This is a collection of methods that assist in dealing with form controls. They provide ways to Form.Element.focus, Form.Element.serialize, Form.Element.disable/Form.Element.enable or extract current value from a specific control.

      Note that nearly all these methods are available directly on input, select, and textarea elements. Therefore, these are equivalent:

      Form.Element.activate('myfield');
      $('myfield').activate();
      

      Naturally, you should always prefer the shortest form suitable in a situation. Most of these methods also return the element itself (as indicated by the return type) for chainability.

      Classes

      Form.Element.EventObserver

      Form.Element.Observer

      Description

      An Abstract.TimedObserver subclass that watches for changes to a form field's value. This triggers the callback when the form field's value (according to Form.Element.getValue) changes. (Note that when the value actually changes can vary from browser to browser, particularly with select boxes.)

      Form.Element observer implements the getValue() method using Form.Element.getValue on the given element. See Abstract.TimedObserver for general documentation on timed observers.

      Form.Element.Observer.new

        • new Form.Element.Observer(element, frequency, callback)
        • element
          • String
          • Element
        • The form element to watch. Can be an element instance or an ID.

        • frequency
          • Number
        • The frequency, in seconds — e.g., 0.33 to check for changes every third of a second.

        • callback
          • Function
        • The callback to trigger when the value changes.

      Creates a Form.Element.Observer.

      Form.Element.activate

        • Form.Element.activate(element)

      Gives focus to a form control and selects its contents if it is a text input.

      This method is just a shortcut for focusing and selecting; therefore, these are equivalent (aside from the fact that the former one will not return the field) :

      Form.Element.focus('myelement').select()
      $('myelement').activate()
      

      Guess which call is the nicest? ;)

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form.Element.clear

      Clears the contents of a text input. Returns the element.

      Example

      This code sets up a text field in a way that it clears its contents the first time it receives focus:

        $('some_field').onfocus = function() {
          // if already cleared, do nothing
          if (this._cleared) return
      
          // when this code is executed, "this" keyword will in fact be the field itself
          this.clear()
          this._cleared = true
        }

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form.Element.disable

        • Form.Element.disable(element)

      Disables a form control, effectively preventing its value from changing until it is enabled again.

      This method sets the native disabled property of an element to true. You can use this property to check the state of a control.

      Notes

      Disabled form controls are never serialized.

      Never disable a form control as a security measure without having validation for it server-side. A user with minimal experience of JavaScript can enable these fields on your site easily using any browser. Instead, use disabling as a usability enhancement - with it you can indicate that a specific value should not be changed at the time being.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form.Element.enable

        • Form.Element.enable(element)

      Enables a previously disabled form control.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form.Element.focus

      Gives keyboard focus to an element. Returns the element.

      Example
      Form.Element.focus('searchbox')
      
      // Almost equivalent, but does NOT return the form element (uses the native focus() method):
      $('searchbox').focus()

      Form.Element.getValue

      Returns the current value of a form control.

      A string is returned for most controls; only multiple select boxes return an array of values.

      The global shortcut for this method is $F.

      How to reference form controls by their name

      This method is consistent with other DOM extensions in that it requires an element ID as the string argument, not the name of the form control (as some might think). If you want to reference controls by their names, first find the control the regular JavaScript way and use the node itself instead of an ID as the argument.

      For example, if you have an input named "company" in a form with an ID "contact":

      var form = $('contact');
      var input = form['company'];
      
      Form.Element.getValue(input);
      
      // but, the preferred call is:
      $(input).getValue(); // we used the $() method so the node gets extended
      
      // you can also use the shortcut
      $F(input);
      
      Note

      An error is thrown ("element has no properties") if the element argument is an unknown ID.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Alias of:

      Form.Element.present

        • Form.Element.present(element)

      Returns true if a text input has contents, false otherwise.

      Example

      This method is very handy in a generic form validation routine. On the following form's submit event, the presence of each text input is checked and lets the user know if they left a text input blank.

      language: html
      <form id="example" class="example" action="#">
        <fieldset>
          <legend>User Details</legend>
          <p id="msg" class="message">Please fill out the following fields:</p>
          <p>
            <label for="username">Username</label>
            <input id="username" type="text" name="username" />
          </p>
          <p>
            <label for="email">Email Address</label>
            <input id="email" type="text" name="email" />
          </p>
          <input type="submit" value="submit" />
        </fieldset>
      </form>
      
      <script type="text/javascript">
        $('example').onsubmit = function(){
          var valid, msg = $('msg')
      
          // are both fields present?
          valid = $(this.username).present() && $(this.email).present()
      
          if (valid) {
            // in the real world we would return true here to allow the form to be submitted
            // return true
            msg.update('Passed validation!').style.color = 'green'
          } else {
            msg.update('Please fill out <em>all</em> the fields.').style.color = 'red'
          }
          return false
        }
      </script>      

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form.Element.select

        • Form.Element.select(element)

      Selects the current text in a text input. Returns the element.

      Example

      Some search boxes are set up so that they auto-select their content when they receive focus.

        $('searchbox').onfocus = function() {
          Form.Element.select(this)
      
          // You can also rely on the native method, but this will NOT return the element!
          this.select()
        }
      
      Focusing + selecting: use Form.Element.activate!

      The Form.Element.activate method is a nifty way to both focus a form field and select its current text, all in one portable JavaScript call.

      Form.Element.serialize

        • Form.Element.serialize(element)

      Returns a URL-encoded string representation of a form control in the name=value format.

      The result of this method is a string suitable for Ajax requests. However, it serializes only a single element - if you need to serialize the whole form use Form.serialize instead.

      Notes

      Serializing a disabled control or a one without a name will always result in an empty string.

      If you simply need an element's value for reasons other than Ajax requests, use Form.Element.getValue instead.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form.Element.setValue

        • Form.Element.setValue(element, value)

      Sets value to be the value of the form control. Returns the element.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form.Element#activate

      Gives focus to a form control and selects its contents if it is a text input.

      This method is just a shortcut for focusing and selecting; therefore, these are equivalent (aside from the fact that the former one will not return the field) :

      Form.Element.focus('myelement').select()
      $('myelement').activate()
      

      Guess which call is the nicest? ;)

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form.Element#clear

      Clears the contents of a text input. Returns the element.

      Example

      This code sets up a text field in a way that it clears its contents the first time it receives focus:

        $('some_field').onfocus = function() {
          // if already cleared, do nothing
          if (this._cleared) return
      
          // when this code is executed, "this" keyword will in fact be the field itself
          this.clear()
          this._cleared = true
        }

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form.Element#disable

      Disables a form control, effectively preventing its value from changing until it is enabled again.

      This method sets the native disabled property of an element to true. You can use this property to check the state of a control.

      Notes

      Disabled form controls are never serialized.

      Never disable a form control as a security measure without having validation for it server-side. A user with minimal experience of JavaScript can enable these fields on your site easily using any browser. Instead, use disabling as a usability enhancement - with it you can indicate that a specific value should not be changed at the time being.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form.Element#enable

      Enables a previously disabled form control.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form.Element#getValue

      Returns the current value of a form control.

      A string is returned for most controls; only multiple select boxes return an array of values.

      The global shortcut for this method is $F.

      How to reference form controls by their name

      This method is consistent with other DOM extensions in that it requires an element ID as the string argument, not the name of the form control (as some might think). If you want to reference controls by their names, first find the control the regular JavaScript way and use the node itself instead of an ID as the argument.

      For example, if you have an input named "company" in a form with an ID "contact":

      var form = $('contact');
      var input = form['company'];
      
      Form.Element.getValue(input);
      
      // but, the preferred call is:
      $(input).getValue(); // we used the $() method so the node gets extended
      
      // you can also use the shortcut
      $F(input);
      
      Note

      An error is thrown ("element has no properties") if the element argument is an unknown ID.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Alias of:

      Form.Element#present

      Returns true if a text input has contents, false otherwise.

      Example

      This method is very handy in a generic form validation routine. On the following form's submit event, the presence of each text input is checked and lets the user know if they left a text input blank.

      language: html
      <form id="example" class="example" action="#">
        <fieldset>
          <legend>User Details</legend>
          <p id="msg" class="message">Please fill out the following fields:</p>
          <p>
            <label for="username">Username</label>
            <input id="username" type="text" name="username" />
          </p>
          <p>
            <label for="email">Email Address</label>
            <input id="email" type="text" name="email" />
          </p>
          <input type="submit" value="submit" />
        </fieldset>
      </form>
      
      <script type="text/javascript">
        $('example').onsubmit = function(){
          var valid, msg = $('msg')
      
          // are both fields present?
          valid = $(this.username).present() && $(this.email).present()
      
          if (valid) {
            // in the real world we would return true here to allow the form to be submitted
            // return true
            msg.update('Passed validation!').style.color = 'green'
          } else {
            msg.update('Please fill out <em>all</em> the fields.').style.color = 'red'
          }
          return false
        }
      </script>      

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form.Element#serialize

        • Form.Element#serialize()

      Returns a URL-encoded string representation of a form control in the name=value format.

      The result of this method is a string suitable for Ajax requests. However, it serializes only a single element - if you need to serialize the whole form use Form.serialize instead.

      Notes

      Serializing a disabled control or a one without a name will always result in an empty string.

      If you simply need an element's value for reasons other than Ajax requests, use Form.Element.getValue instead.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form.Element#setValue

        • Form.Element#setValue(value)

      Sets value to be the value of the form control. Returns the element.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form.EventObserver

      Form.Observer

      Description

      An Abstract.TimedObserver subclass that watches for changes to a form. The callback is triggered when the form changes — e.g., when any of its fields' values changes, when fields are added/removed, etc.; anything that affects the serialized form of the form (see Form#serialize).

      Example

      In this example an observer is used to change the appearance of the form if any of the values had been changed. It returns to its initial state when the data is submitted (saved).

      language: html
      <form id="example" action="#">
        <fieldset>
          <legend>Login Preferences</legend>
          <p id="msg" class="message">Current settings:</p>
          <p>
            <label for="greeting">Greeting message</label>
            <input id="greeting" type="text" name="greeting" value="Hello world!" />
          </p>
          <h4>Login options</h4>
          <p>
              <input id="login-visible" type="checkbox" name="login-visible" checked="checked" />
              <label for="login-visible">allow others to see my last login date</label>
          </p>
          <p>
              <input id="land-recent" type="checkbox" name="land-recent" />
              <label for="land-recent">land on recent changes overview instead of the Dashboard</label>
          </p>
          <input type="submit" value="save" />
        </fieldset>
      </form>
      
      <script type="text/javascript">
        new Form.Observer('example', 0.3, function(form, value){
          $('msg').update('Your preferences have changed. Resubmit to save').style.color = 'red'
          form.down().setStyle({ background:'lemonchiffon', borderColor:'red' })
        })
      
        $('example').onsubmit = function() {
          $('msg').update('Preferences saved!').style.color = 'green'
          this.down().setStyle({ background:null, borderColor:null })
          return false
        }
      </script>

      Form.Observer.new

        • new Form.Observer(element, frequency, callback)
        • element
          • String
          • Element
        • The element of the form to watch. Can be an element instance or an ID.

        • frequency
          • Number
        • The frequency, in seconds -- e.g., 0.33 to check for changes every third of a second.

        • callback
          • Function
        • The callback to trigger when the form changes.

      Creates a Form.Observer.

      Form.disable

      Disables the form as a whole. Form controls will be visible but uneditable.

      Disabling the form is done by iterating over form elements and calling Form.Element.disable on them.

      Note

      Keep in mind that disabled elements are skipped by serialization methods! You cannot serialize a disabled form.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form.enable

      Enables a fully- or partially-disabled form.

      Enabling the form is done by iterating over form elements and calling Form.Element.enable on them.

      Note

      This will enable all form controls regardless of how they were disabled (by scripting or by HTML attributes).

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form.findFirstElement

      Finds the first non-hidden, non-disabled control within the form.

      The returned object is either an INPUT, SELECT or TEXTAREA element. This method is used by the Form.focusFirstElement method.

      Note

      The result of this method is the element that comes first in the document order, not the tabindex order.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form.focusFirstElement

        • Form.focusFirstElement(form)

      Gives keyboard focus to the first element of the form. Returns the form.

      Uses Form.findFirstElement to get the first element and calls Form.Element.activate on it. This is useful for enhancing usability on your site by bringing focus on page load to forms such as search forms or contact forms where a user is ready to start typing right away.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form.getElements

        • Form.getElements(form)

      Returns a collection of all controls within a form.

      Note

      OPTION elements are not included in the result; only their parent SELECT control is.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form.getInputs

        • Form.getInputs(form[, type][, name])
        • type
          • String
        • A value for the type attribute against which to filter.

        • name
          • String
        • A value for the name attribute against which to filter.

      Returns a collection of all INPUT elements in a form.

      Use optional type and name arguments to restrict the search on these attributes.

      Example
      var form = $('myform');
      
      form.getInputs();       // -> all INPUT elements
      form.getInputs('text'); // -> only text inputs
      
      var buttons = form.getInputs('radio', 'education');
      // -> only radio buttons of name "education"
      
      // now disable these radio buttons:
      buttons.invoke('disable');
      
      Note

      Elements are returned in the document order, not the tabindex order.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form.request

        • Form.request(form[, options])
        • options
          • Object
        • Options to pass along to the Ajax.Request constructor.

      A convenience method for serializing and submitting the form via an Ajax.Request to the URL of the form's action attribute.

      The options parameter is passed to the Ajax.Request instance, allowing one to override the HTTP method and/or specify additional parameters and callbacks.

      • If the form has a method attribute, its value is used for the Ajax.Request method option. If a method option is passed to request(), it takes precedence over the form's method attribute. If neither is specified, method defaults to "POST".

      • Key-value pairs specified in the parameters option (either as a hash or a query string) will be merged with (and take precedence over) the serialized form parameters.

      Example

      Suppose you have this HTML form:

      language: html
      <form id="person-example" method="POST" action="/user/info">
        <fieldset><legend>User info</legend>
          <ul>
            <li>
              <label for="username">Username:</label>
              <input type="text" name="username" id="username" value="" />
            </li>
            <li>
              <label for="age">Age:</label>
              <input type="text" name="age" id="age" value="" size="3" />
            </li>
            <li>
              <label for="hobbies">Your hobbies are:</label>
              <select name="hobbies[]" id="hobbies" multiple="multiple">
                <option>coding</option>
                <option>swimming</option>
                <option>biking</option>
                <option>hiking</option>
                <option>drawing</option>
              </select>
            </li>
          </ul>
          <input type="submit" value="serialize!" />
        </fieldset>
      </form>
      

      You can easily post it with Ajax like this:

      $('person-example').request(); //done - it's posted
      
      // do the same with a callback:
      $('person-example').request({
        onComplete: function(){ alert('Form data saved!') }
      })
      

      To override the HTTP method and add some parameters, simply use method and parameters in the options. In this example we set the method to GET and set two fixed parameters: interests and hobbies. The latter already exists in the form but this value will take precedence.

      $('person-example').request({
        method: 'get',
        parameters: { interests:'JavaScript', 'hobbies[]':['programming', 'music'] },
        onComplete: function(){ alert('Form data saved!') }
      })

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form.reset

      Resets a form to its default values.

      Example usage:

      Form.reset('contact')
      
      // equivalent:
      $('contact').reset()
      
      // both have the same effect as pressing the reset button
      

      This method allows you to programatically reset a form. It is a wrapper for the reset() method native to HTMLFormElement.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form.serialize

        • options
          • Object
        • A list of options that affect the return value of the method.

      Serializes form data to a string suitable for Ajax requests (default behavior) or, if the hash option evaluates to true, an object hash where keys are form control names and values are data.

      Depending of whether or not the hash option evaluates to true, the result is either an object of the form {name: "johnny", color: "blue"} or a String of the form "name=johnny&color=blue", suitable for parameters in an Ajax request. This method mimics the way browsers serialize forms natively so that form data can be sent without refreshing the page.

      See Form.serializeElements for more details on the options.

      Examples
      $('person-example').serialize()
      // -> 'username=sulien&age=22&hobbies=coding&hobbies=hiking'
      
      $('person-example').serialize(true)
      // -> {username: 'sulien', age: '22', hobbies: ['coding', 'hiking']}
      
      Notes

      Disabled form elements are not serialized (as per W3C HTML recommendation). Also, file inputs are skipped as they cannot be serialized and sent using only JavaScript.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form.serializeElements

        • elements
          • Array
        • A collection of elements to include in the serialization.

        • options
          • Object
        • (Optional) A set of options that affect the return value of the method.

      Serialize an array of form elements to an object or string suitable for Ajax requests.

      As per the HTML spec, disabled fields are not included.

      If multiple elements have the same name and we're returning an object, the value for that key in the object will be an array of the field values in the order they appeared on the array of elements.

      The preferred method to serialize a form is Form.serialize. Refer to it for further information and examples on the hash option. However, with Form.serializeElements you can serialize specific input elements of your choice, allowing you to specify a subset of form elements that you want to serialize data from.

      The Options

      The options allow you to control two things: What kind of return value you get (an object or a string), and whether and which submit fields are included in that object or string.

      If you do not supply an options object at all, the options { hash: false } are used.

      If you supply an options object, it may have the following options:

      • hash ([[Boolean]]): true to return a plain object with keys and values (not a Hash; see below), false to return a String in query string format. If you supply an options object with no hash member, hash defaults to true. Note that this is not the same as leaving off the options object entirely (see above).

      • submit ([[Boolean]] | String): In essence: If you omit this option the first submit button in the form is included; if you supply false, no submit buttons are included; if you supply the name of a submit button, the first button with that name is included. Note that the false value must really be false, not falsey; falsey-but-not-false is like omitting the option.

      (Deprecated) If you pass in a [[Boolean]] instead of an object for options, it is used as the hash option and all other options are defaulted.

      A hash, not a Hash

      If you opt to receive an object, it is a plain JavaScript object with keys and values, not a Hash. All JavaScript objects are hashes in the lower-case sense of the word, which is why the option has that somewhat-confusing name.

      Examples

      To serialize all input elements of type "text":

      Form.serializeElements( $('myform').getInputs('text') )
      // -> serialized data

      Form#disable

      Disables the form as a whole. Form controls will be visible but uneditable.

      Disabling the form is done by iterating over form elements and calling Form.Element.disable on them.

      Note

      Keep in mind that disabled elements are skipped by serialization methods! You cannot serialize a disabled form.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form#enable

      Enables a fully- or partially-disabled form.

      Enabling the form is done by iterating over form elements and calling Form.Element.enable on them.

      Note

      This will enable all form controls regardless of how they were disabled (by scripting or by HTML attributes).

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form#findFirstElement

      Finds the first non-hidden, non-disabled control within the form.

      The returned object is either an INPUT, SELECT or TEXTAREA element. This method is used by the Form.focusFirstElement method.

      Note

      The result of this method is the element that comes first in the document order, not the tabindex order.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form#focusFirstElement

      Gives keyboard focus to the first element of the form. Returns the form.

      Uses Form.findFirstElement to get the first element and calls Form.Element.activate on it. This is useful for enhancing usability on your site by bringing focus on page load to forms such as search forms or contact forms where a user is ready to start typing right away.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form#getElements

      Returns a collection of all controls within a form.

      Note

      OPTION elements are not included in the result; only their parent SELECT control is.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form#getInputs

        • Form#getInputs([type][, name])
        • type
          • String
        • A value for the type attribute against which to filter.

        • name
          • String
        • A value for the name attribute against which to filter.

      Returns a collection of all INPUT elements in a form.

      Use optional type and name arguments to restrict the search on these attributes.

      Example
      var form = $('myform');
      
      form.getInputs();       // -> all INPUT elements
      form.getInputs('text'); // -> only text inputs
      
      var buttons = form.getInputs('radio', 'education');
      // -> only radio buttons of name "education"
      
      // now disable these radio buttons:
      buttons.invoke('disable');
      
      Note

      Elements are returned in the document order, not the tabindex order.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form#request

        • options
          • Object
        • Options to pass along to the Ajax.Request constructor.

      A convenience method for serializing and submitting the form via an Ajax.Request to the URL of the form's action attribute.

      The options parameter is passed to the Ajax.Request instance, allowing one to override the HTTP method and/or specify additional parameters and callbacks.

      • If the form has a method attribute, its value is used for the Ajax.Request method option. If a method option is passed to request(), it takes precedence over the form's method attribute. If neither is specified, method defaults to "POST".

      • Key-value pairs specified in the parameters option (either as a hash or a query string) will be merged with (and take precedence over) the serialized form parameters.

      Example

      Suppose you have this HTML form:

      language: html
      <form id="person-example" method="POST" action="/user/info">
        <fieldset><legend>User info</legend>
          <ul>
            <li>
              <label for="username">Username:</label>
              <input type="text" name="username" id="username" value="" />
            </li>
            <li>
              <label for="age">Age:</label>
              <input type="text" name="age" id="age" value="" size="3" />
            </li>
            <li>
              <label for="hobbies">Your hobbies are:</label>
              <select name="hobbies[]" id="hobbies" multiple="multiple">
                <option>coding</option>
                <option>swimming</option>
                <option>biking</option>
                <option>hiking</option>
                <option>drawing</option>
              </select>
            </li>
          </ul>
          <input type="submit" value="serialize!" />
        </fieldset>
      </form>
      

      You can easily post it with Ajax like this:

      $('person-example').request(); //done - it's posted
      
      // do the same with a callback:
      $('person-example').request({
        onComplete: function(){ alert('Form data saved!') }
      })
      

      To override the HTTP method and add some parameters, simply use method and parameters in the options. In this example we set the method to GET and set two fixed parameters: interests and hobbies. The latter already exists in the form but this value will take precedence.

      $('person-example').request({
        method: 'get',
        parameters: { interests:'JavaScript', 'hobbies[]':['programming', 'music'] },
        onComplete: function(){ alert('Form data saved!') }
      })

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form#reset

      Resets a form to its default values.

      Example usage:

      Form.reset('contact')
      
      // equivalent:
      $('contact').reset()
      
      // both have the same effect as pressing the reset button
      

      This method allows you to programatically reset a form. It is a wrapper for the reset() method native to HTMLFormElement.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Form#serialize

        • options
          • Object
        • A list of options that affect the return value of the method.

      Serializes form data to a string suitable for Ajax requests (default behavior) or, if the hash option evaluates to true, an object hash where keys are form control names and values are data.

      Depending of whether or not the hash option evaluates to true, the result is either an object of the form {name: "johnny", color: "blue"} or a String of the form "name=johnny&color=blue", suitable for parameters in an Ajax request. This method mimics the way browsers serialize forms natively so that form data can be sent without refreshing the page.

      See Form.serializeElements for more details on the options.

      Examples
      $('person-example').serialize()
      // -> 'username=sulien&age=22&hobbies=coding&hobbies=hiking'
      
      $('person-example').serialize(true)
      // -> {username: 'sulien', age: '22', hobbies: ['coding', 'hiking']}
      
      Notes

      Disabled form elements are not serialized (as per W3C HTML recommendation). Also, file inputs are skipped as they cannot be serialized and sent using only JavaScript.

      This method can be called either as an instance method or as a generic method. If calling as generic, pass the instance in as the first argument.

      Selector

      Deprecated

      Description

      A class that queries the document for elements that match a given CSS selector.

      Constructor

      Instance methods

      Selector.new

      Deprecated
        • new Selector(expression)
        • expression
          • String
        • A CSS selector.

      Creates a Selector with the given CSS selector.

      Selector.findChildElements

      Deprecated
        • Selector.findChildElements(element, expressions)

      Searches beneath element for any elements that match the selector (or selectors) specified in expressions.

      Selector.findElement

      Deprecated
        • Selector.findElement
        • Selector.findElement(elements[, index = 0])

      Returns the indexth element in the collection that matches expression.

      Returns the indexth element overall if expression is not given.

      Selector.matchElements

      Deprecated
        • Selector.matchElements(elements, expression)

      Filters the given collection of elements with expression.

      The only nodes returned will be those that match the given CSS selector.

      Selector#findElements

      Deprecated
        • Selector#findElements(root)
        • root
          • Element
          • document
        • A "scope" to search within. All results will be descendants of this node.

      Searches the document for elements that match the instance's CSS selector.

      Selector#match

      Deprecated
        • Selector#match(element)
          • Boolean

      Tests whether a element matches the instance's CSS selector.

      Language section

      Description

      Additions to JavaScript's "standard library" and extensions to built-in JavaScript objects.

      Namespaces

      Classes

      • Array

        Prototype extends all native JavaScript arrays with quite a few powerful methods.

      • Class

        Manages Prototype's class-based OOP system.

      • Date

        Extensions to the built-in Date object.

      • Function

        Extensions to the built-in Function object.

      • Hash

        A set of key/value pairs.

      • Number

        Extensions to the built-in Number object.

      • Object

        Extensions to the built-in Object object.

      • ObjectRange

        A succession of values.

      • PeriodicalExecuter

        Oversees the calling of a particular function periodically.

      • RegExp

        Extensions to the built-in RegExp object.

      • String

        Extensions to the built-in String class.

      • Template

        A class for sophisticated string interpolation.

      Mixins

      • Enumerable

        Enumerable provides a large set of useful methods for enumerations — objects that act as collections of values. It is a cornerstone of Prototype.

      Utilities

      Array

      Description

      Prototype extends all native JavaScript arrays with quite a few powerful methods.

      This is done in two ways:

      • It mixes in the Enumerable module, which brings in a ton of methods.
      • It adds quite a few extra methods, which are documented in this section.

      With Prototype, arrays become much, much more than the trivial objects we used to manipulate, limiting ourselves to using their length property and their [] indexing operator. They become very powerful objects that greatly simplify the code for 99% of the common use cases involving them.

      Why you should stop using for...in to iterate

      Many JavaScript authors have been misled into using the for...in JavaScript construct to loop over array elements. This kind of code just won't work with Prototype.

      The ECMA 262 standard, which defines ECMAScript 3rd edition, supposedly implemented by all major browsers including MSIE, defines ten methods on Array (§15.4.4), including nice methods like concat, join, pop, and push.

      This same standard explicitly defines that the for...in construct (§12.6.4) exists to enumerate the properties of the object appearing on the right side of the in keyword. Only properties specifically marked as non-enumerable are ignored by such a loop. By default, the prototype and length properties are so marked, which prevents you from enumerating over array methods when using for...in. This comfort led developers to use for...in as a shortcut for indexing loops, when it is not its actual purpose.

      However, Prototype has no way to mark the methods it adds to Array.prototype as non-enumerable. Therefore, using for...in on arrays when using Prototype will enumerate all extended methods as well, such as those coming from the Enumerable module, and those Prototype puts in the Array namespace (listed further below).

      What you should use instead

      You can revert to vanilla loops:

      for (var index = 0; index < myArray.length; ++index) {
        var item = myArray[index];
        // Your code working on item here...
      }
      

      Or you can use iterators, such as [[Array#each]]:

      myArray.each(function(item) {
        // Your code working on item here...
      });
      

      The inability to use for...in on arrays is not much of a burden: as you'll see, most of what you used to loop over arrays for can be concisely done using the new methods provided by Array or the mixed-in Enumerable module. So manual loops should be fairly rare.

      A note on performance

      Should you have a very large array, using iterators with lexical closures (anonymous functions that you pass to the iterators and that get invoked at every loop iteration) in methods like [[Array#each]] — or relying on repetitive array construction (such as uniq), may yield unsatisfactory performance. In such cases, you're better off writing manual indexing loops, but take care then to cache the length property and use the prefix ++ operator:

      // Custom loop with cached length property: maximum full-loop
      // performance on very large arrays!
      for (var index = 0, len = myArray.length; index < len; ++index) {
        var item = myArray[index];
        // Your code working on item here...
      }
      

      Includes

      Class methods

      Array.from

        • Array.from(iterable)
      Alias of:

      Array#clear

      Clears the array (makes it empty) and returns the array reference.

      Example
      var guys = ['Sam', 'Justin', 'Andrew', 'Dan'];
      guys.clear();
      // -> []
      guys
      // -> []

      Array#clone

      Returns a duplicate of the array, leaving the original array intact.

      Aliased as:

      Array#compact

      Returns a copy of the array without any null or undefined values.

      Example
      var orig = [undefined, 'A', undefined, 'B', null, 'C'];
      var copy = orig.compact();
      // orig -> [undefined, 'A', undefined, 'B', null, 'C'];
      // copy -> ['A', 'B', 'C'];

      Array#first

        • Array#first()
          • ?

      Returns the array's first item (e.g., array[0]).

      Array#flatten

      Returns a flattened (one-dimensional) copy of the array, leaving the original array unchanged.

      Nested arrays are recursively injected inline. This can prove very useful when handling the results of a recursive collection algorithm, for instance.

      Example
      var a = ['frank', ['bob', 'lisa'], ['jill', ['tom', 'sally']]];
      var b = a.flatten();
      // a -> ['frank', ['bob', 'lisa'], ['jill', ['tom', 'sally']]]
      // b -> ['frank', 'bob', 'lisa', 'jill', 'tom', 'sally']

      Array#indexOf

        • Array#indexOf(item[, offset = 0])
        • item
          • A value that may or may not be in the array.

          • offset
            • Number
          • The number of initial items to skip before beginning the search.

        Returns the index of the first occurrence of item within the array, or -1 if item doesn't exist in the array. Array#indexOf compares items using strict equality (===).

        Examples
        [3, 5, 6, 1, 20].indexOf(1)
        // -> 3
        
        [3, 5, 6, 1, 20].indexOf(90)
        // -> -1 (not found)
        
        ['1', '2', '3'].indexOf(1);
        // -> -1 (not found, 1 !== '1')

        Array#inspect

        Returns the debug-oriented string representation of an array.

        Example
        ['Apples', {good: 'yes', bad: 'no'}, 3, 34].inspect()
        // -> "['Apples', [object Object], 3, 34]"

        Array#intersect

          • Array#intersect(array)
          • array
            • Array
          • A collection of values.

        Returns an array containing every item that is shared between the two given arrays.

        Array#last

          • Array#last()
            • ?

        Returns the array's last item (e.g., array[array.length - 1]).

        Array#lastIndexOf

          • Array#lastIndexOf(item[, offset])
          • item
            • A value that may or may not be in the array.

            • offset
              • Number
            • The number of items at the end to skip before beginning the search.

          Returns the position of the last occurrence of item within the array — or -1 if item doesn't exist in the array.

          Array#reverse

            • Array#reverse([inline = true])
            • inline
              • Boolean
            • Whether to modify the array in place. Defaults to true. Clones the original array when false.

          Reverses the array's contents, optionally cloning it first.

          Examples
          // Making a copy
          var nums = [3, 5, 6, 1, 20];
          var rev = nums.reverse(false);
          // nums -> [3, 5, 6, 1, 20]
          // rev -> [20, 1, 6, 5, 3]
          
          // Working inline
          var nums = [3, 5, 6, 1, 20];
          nums.reverse();
          // nums -> [20, 1, 6, 5, 3]

          Array#size

          Returns the size of the array (e.g., array.length).

          This is just a local optimization of the mixed-in Enumerable#size which avoids array cloning and uses the array's native length property.

          Array#toArray

          Alias of:

          Array#uniq

            • Array#uniq([sorted = false])
            • sorted
              • Boolean
            • Whether the array has already been sorted. If true, a less-costly algorithm will be used.

          Produces a duplicate-free version of an array. If no duplicates are found, the original array is returned.

          On large arrays when sorted is false, this method has a potentially large performance cost.

          Examples
          [1, 3, 2, 1].uniq();
          // -> [1, 2, 3]
          
          ['A', 'a'].uniq();
          // -> ['A', 'a'] (because String comparison is case-sensitive)

          Array#without

            • Array#without(value[, value...])
            • value
              • A value to exclude.

            Produces a new version of the array that does not contain any of the specified values, leaving the original array unchanged.

            Examples
            [3, 5, 6].without(3)
            // -> [5, 6]
            
            [3, 5, 6, 20].without(20, 6)
            // -> [3, 5]

            Class

            Description

            Manages Prototype's class-based OOP system.

            Refer to Prototype's web site for a tutorial on classes and inheritance.

            Class methods

            Instance methods

            Class.create

              • Class.create([superclass][, methods...])
              • superclass
                • Class
              • The optional superclass to inherit methods from.

              • methods
                • Object
              • An object whose properties will be "mixed-in" to the new class. Any number of mixins can be added; later mixins take precedence.

            Class.create creates a class and returns a constructor function for instances of the class. Calling the constructor function (typically as part of a new statement) will invoke the class's initialize method.

            Class.create accepts two kinds of arguments. If the first argument is a Class, it's used as the new class's superclass, and all its methods are inherited. Otherwise, any arguments passed are treated as objects, and their methods are copied over ("mixed in") as instance methods of the new class. In cases of method name overlap, later arguments take precedence over earlier arguments.

            If a subclass overrides an instance method declared in a superclass, the subclass's method can still access the original method. To do so, declare the subclass's method as normal, but insert $super as the first argument. This makes $super available as a method for use within the function.

            To extend a class after it has been defined, use Class#addMethods.

            For details, see the inheritance tutorial on the Prototype website.

            Class#addMethods

              • Class#addMethods(methods)
              • methods
                • Object
              • The methods to add to the class.

            Adds methods to an existing class.

            Class#addMethods is a method available on classes that have been defined with Class.create. It can be used to add new instance methods to that class, or overwrite existing methods, after the class has been defined.

            New methods propagate down the inheritance chain. If the class has subclasses, those subclasses will receive the new methods — even in the context of $super calls. The new methods also propagate to instances of the class and of all its subclasses, even those that have already been instantiated.

            Examples
            var Animal = Class.create({
              initialize: function(name, sound) {
                this.name  = name;
                this.sound = sound;
              },
            
              speak: function() {
                alert(this.name + " says: " + this.sound + "!");
              }
            });
            
            // subclassing Animal
            var Snake = Class.create(Animal, {
              initialize: function($super, name) {
                $super(name, 'hissssssssss');
              }
            });
            
            var ringneck = new Snake("Ringneck");
            ringneck.speak();
            
            //-> alerts "Ringneck says: hissssssss!"
            
            // adding Snake#speak (with a supercall)
            Snake.addMethods({
              speak: function($super) {
                $super();
                alert("You should probably run. He looks really mad.");
              }
            });
            
            ringneck.speak();
            //-> alerts "Ringneck says: hissssssss!"
            //-> alerts "You should probably run. He looks really mad."
            
            // redefining Animal#speak
            Animal.addMethods({
              speak: function() {
                alert(this.name + 'snarls: ' + this.sound + '!');
              }
            });
            
            ringneck.speak();
            //-> alerts "Ringneck snarls: hissssssss!"
            //-> alerts "You should probably run. He looks really mad."

            Date

            Description

            Extensions to the built-in Date object.

            Instance methods

            Date#toISOString

            Produces a string representation of the date in ISO 8601 format. The time zone is always UTC, as denoted by the suffix "Z".

            <h5>Example</h5>

            var d = new Date(1969, 11, 31, 19);
            d.getTimezoneOffset();
            //-> -180 (time offest is given in minutes.)
            d.toISOString();
            //-> '1969-12-31T16:00:00Z'

            Date#toJSON

            Internally calls Date#toISOString.

            <h5>Example</h5>

            var d = new Date(1969, 11, 31, 19);
            d.getTimezoneOffset();
            //-> -180 (time offest is given in minutes.)
            d.toJSON();
            //-> '1969-12-31T16:00:00Z'

            Enumerable

            Description

            Enumerable provides a large set of useful methods for enumerations — objects that act as collections of values. It is a cornerstone of Prototype.

            Enumerable is a mixin: a set of methods intended not for standaone use, but for incorporation into other objects.

            Prototype mixes Enumerable into several classes. The most visible cases are Array and Hash, but you'll find it in less obvious spots as well, such as in ObjectRange and various DOM- or Ajax-related objects.

            The context parameter

            Every method of Enumerable that takes an iterator also takes the "context object" as the next (optional) parameter. The context object is what the iterator will be bound to — what the keyword this will refer to inside the iterator.

            var myObject = {};
            
            ['foo', 'bar', 'baz'].each(function(name, index) {
              this[name] = index;
            }, myObject); // we have specified the context
            
            myObject;
            // -> { foo: 0, bar: 1, baz: 2}
            

            If there is no context argument, the iterator function will execute in the scope from which the Enumerable method itself was called.

            Mixing Enumerable into your own objects

            So, let's say you've created your very own collection-like object (say, some sort of Set, or perhaps something that dynamically fetches data ranges from the server side, lazy-loading style). You want to be able to mix Enumerable in (and we commend you for it). How do you go about this?

            The Enumerable module basically makes only one requirement on your object: it must provide a method named _each (note the leading underscore) that will accept a function as its unique argument, and will contain the actual "raw iteration" algorithm, invoking its argument with each element in turn.

            As detailed in the documentation for Enumerable#each, Enumerable provides all the extra layers (handling iteration short-circuits, passing numeric indices, etc.). You just need to implement the actual iteration, as fits your internal structure.

            If you're still confused, just have a look at the Prototype source code for Array, Hash, or ObjectRange. They all begin with their own _each method, which should help you grasp the idea.

            Once you're done with this, you just need to mix Enumerable in, which you'll usually do before defining your methods, so as to make sure whatever overrides you provide for Enumerable methods will indeed prevail. In short, your code will probably end up looking like this:

            var YourObject = Class.create(Enumerable, {
              initialize: function() { // with whatever constructor arguments you need
                // Your construction code
              },
            
              _each: function(iterator) {
                // Your iteration code, invoking iterator at every turn
              },
            
              // Your other methods here, including Enumerable overrides
            });
            

            Then, obviously, your object can be used like this:

            var obj = new YourObject();
            // Populate the collection somehow
            obj.pluck('somePropName');
            obj.invoke('someMethodName');
            obj.size();
            // etc.