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.

namespace

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 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 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 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 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

namespace

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.
namespace

Prototype.BrowserFeatures

Description

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

class property

Prototype.BrowserFeatures.ElementExtensions

    • Prototype.BrowserFeatures.ElementExtensions
      • Boolean

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

class property

Prototype.BrowserFeatures.SelectorsAPI

    • Prototype.BrowserFeatures.SelectorsAPI
      • Boolean

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

class property

Prototype.BrowserFeatures.XPath

    • Prototype.BrowserFeatures.XPath
      • Boolean

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

namespace

Prototype.Selector

Description

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

class method

Prototype.Selector.extendElement

    • Prototype.Selector.extendElement(element)
class method

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.

class method

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).

class method

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.

class method

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.

class method

Prototype.emptyFunction

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

The 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.

class method

Prototype.K

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

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
class property

Prototype.Version

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

section

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 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 responseText and populates 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 responseText before evaluating it.
Common callbacks

When used on individual instances, all callbacks (except onException) are invoked with two parameters: the 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 Request.

  • onCreate: Triggered when the 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 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

namespace

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

class

Ajax.PeriodicalUpdater

Description

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

PeriodicalUpdater behaves like Updater, but performs the update at a prescribed interval, rather than only once. (Note that it is not a subclass of 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 Updater at regular intervals, keeping track of the response text so it can (optionally) react to receiving the exact same response consecutively.

Additional options

PeriodicalUpdater features all the common options and callbacks described in the Ajaxplus those added by 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 PeriodicalUpdater

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

Instance methods

constructor

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 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 Updater at regular intervals, monitoring changes in the response text if the decay option (see below) is active.

Additional options

PeriodicalUpdater features all the common options and callbacks (see the Ajax for more information), plus those added by 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?!).

Option Default Description
frequency 2 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.
decay 1 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 frequency 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 does change, the current period resets to the original one.

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
});
Call# When? Decay before Response changed? Decay after Next period Comments
1 00:00 2 n/a 1 3 Response is deemed changed, since there is no prior response to compare to!
2 00:03 1 yes 1 3 Response did change again: we "reset" to 1, which was already the decay.
3 00:06 1 no 2 6 Response didn't change: decay augments by the decay option factor: we're waiting longer now…
4 00:12 2 no 4 12 Still no change, doubling again.
5 00:24 4 no 8 24 Jesus, is this thing going to change or what?
6 00:48 8 yes 1 3 Ah, finally! Resetting decay to 1, and therefore using the original period.
Disabling and re-enabling a PeriodicalUpdater

You can pull the brake on a running 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!

PeriodicalUpdater is not a specialization of Updater, despite its name. When using it, do not expect to be able to use methods normally provided by Request and "inherited" by 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).

instance method

Ajax.PeriodicalUpdater#start

    • Ajax.PeriodicalUpdater#start()
      • undefined

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

instance method

Ajax.PeriodicalUpdater#stop

    • Ajax.PeriodicalUpdater#stop()
      • undefined

Stops the periodical updater.

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

class

Ajax.Request

Description

Initiates and processes an Ajax request.

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 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 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 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 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 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 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

constructor

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.

instance method

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.

instance method

Ajax.Request#success

    • Ajax.Request#success()
      • Boolean

Tests whether the request was successful.

namespace

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 Request, Updater or 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: 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 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 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

class method

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.

class method

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.

class

Ajax.Response

Description

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

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

instance method

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.

instance method

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: getAllHeaders.

instance method

Ajax.Response#getHeader

    • Ajax.Response#getHeader(name)

See getHeader.

instance method

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: getHeader.

instance property

Ajax.Response#headerJSON

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

instance property

Ajax.Response#readyState

    • Ajax.Response#readyState

A Number corresponding to the request's current state.

0 : "Uninitialized"
1 : "Loading"
2 : "Loaded"
3 : "Interactive"
4 : "Complete"

instance property

Ajax.Response#request

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

instance property

Ajax.Response#responseJSON

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

instance property

Ajax.Response#responseText

    • Ajax.Response#responseText

The text body of the response.

instance property

Ajax.Response#responseXML

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

instance property

Ajax.Response#status

The HTTP status code sent by the server.

instance property

Ajax.Response#statusText

    • Ajax.Response#statusText

The HTTP status text sent by the server.

instance property

Ajax.Response#transport

    • Ajax.Response#transport
      • XmlHttpRequest

The native XmlHttpRequest object itself.

class

Ajax.Updater

Description

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

Updater is a subclass of 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

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

Additional options

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 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 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

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.

class property

Ajax.activeRequestCount

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

section

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

utility

$

    • id
      • String
      • Element
    • A DOM node or a string that references a node's ID.

If provided with a string, returns the element in the document with matching ID; otherwise returns the passed element.

Takes in an arbitrary number of arguments. Returns one Element if given one argument; otherwise returns an Array of Elements.

All elements returned by the function are "extended" with Element instance methods.

More Information

The $ function is the cornerstone of Prototype. Not only does it provide a handy alias for document.getElementById, it also lets you pass indifferently IDs (strings) or DOM node references to your functions:

function foo(element) {
    element = $(element);
    //  rest of the function...
}

Code written this way is flexible — you can pass it the ID of the element or the element itself without any type sniffing.

Invoking it with only one argument returns the Element, while invoking it with multiple arguments returns an Array of Elements (and this works recursively: if you're twisted, you could pass it an array containing some arrays, and so forth). As this is dependent on getElementById, W3C specs apply: nonexistent IDs will yield null and IDs present multiple times in the DOM will yield erratic results. If you're assigning the same ID to multiple elements, you're doing it wrong!

The function also extends every returned element with extend so you can use Prototype's DOM extensions on it. In the following code, the two lines are equivalent. However, the second one feels significantly more object-oriented:

// Note quite OOP-like...
Element.hide('itemId');
// A cleaner feel, thanks to guaranted extension
$('itemId').hide();

However, when using iterators, leveraging the $ function makes for more elegant, more concise, and also more efficient code:

['item1', 'item2', 'item3'].each(Element.hide);
// The better way:
$('item1', 'item2', 'item3').invoke('hide');

See How Prototype extends the DOM for more info.

utility

$$

Takes an arbitrary number of CSS selectors (strings) and returns a document-order array of extended DOM elements that match any of them.

Sometimes the usual tools from your DOM arsenal -- document.getElementById encapsulated by $, getElementsByTagName and even Prototype's very own getElementsByClassName extensions -- just aren't enough to quickly find elements or collections of elements. If you know the DOM tree structure, you can simply resort to CSS selectors to get the job done.

Quick examples
$$('div');
// -> all DIVs in the document. Same as document.getElementsByTagName('div').
// Nice addition, the elements you're getting back are already extended!

$$('#contents');
// -> same as $('contents'), only it returns an array anyway (even though IDs must
// be unique within a document).

$$('li.faux');
// -> all LI elements with class 'faux'

The $$ function searches the entire document. For selector queries on more specific sections of a document, use select.

Supported CSS syntax

The $$ function does not rely on the browser's internal CSS parsing capabilities (otherwise, we'd be in cross-browser trouble...), and therefore offers a consistent set of selectors across all supported browsers.

Supported in v1.5.0
  • Type selector: tag names, as in div.
  • Descendant selector: the space(s) between other selectors, as in #a li.
  • Attribute selectors: the full CSS 2.1 set of [attr], [attr=value], [attr~=value] and [attr|=value]. It also supports [attr!=value]. If the value you're matching against includes a space, be sure to enclose the value in quotation marks ([title="Hello World!"]).
  • Class selector: CSS class names, as in .highlighted or .example.wrong.
  • ID selector: as in #item1.
Supported from v1.5.1

Virtually all of CSS3 is supported, with the exception of pseudo-elements (like ::first-letter) and some pseudo-classes (like :hover). Some examples of new selectors that can be used in 1.5.1:

  • Child selector: selects immediate descendants, as in #a > li.
  • Attribute selectors: all attribute operators are supported, including ~= (matches part of a space-delimited attribute value, like rel or class); ^= (matches the beginning of a value); $= (matches the end of a value); and *= (matches any part of the value).
  • The :not pseudo-class, as in #a *:not(li) (matches all descendants of #a that aren't LIs).
  • All the :nth, :first, and :last pseudo-classes. Examples include tr:nth-child(even) (all even table rows), li:first-child (the first item in any list), or p:nth-last-of-type(3) (the third-to-last paragraph on the page).
  • The :empty pseudo-class (for selecting elements without children or text content).
  • The :enabled, :disabled, and :checked pseudo-classes (for use with form controls).
Examples
$$('#contents a[rel]');
// -> all links inside the element of ID "contents" with a rel attribute

$$('a[href="#"]');
// -> all links with a href attribute of value "#" (eyeew!)

$$('#navbar a', '#sidebar a');
// -> all links within the elements of ID "navbar" or "sidebar"

With version 1.5.1 and above you can do various types of advanced selectors:

$$('a:not([rel~=nofollow])');
// -> all links, excluding those whose rel attribute contains the word "nofollow"

$$('table tbody > tr:nth-child(even)');
// -> all even rows within all table bodies

$$('div:empty');
// -> all DIVs without content (i.e., whitespace-only)
utility

$F

Returns the value of a form control. This is a convenience alias of getValue. Refer to it for full details.

namespace

Abstract

Classes

class

Abstract.EventObserver

class

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: Observer, which serializes a form and triggers when the result has changed; and 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 Observer:

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

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 TimedObserver; used by subclasses.

namespace

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

namespace

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.

class method

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 }
class method

document.viewport.getHeight

    • document.viewport.getHeight()

Returns the height of the viewport.

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

class method

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 }
class method

document.viewport.getWidth

    • document.viewport.getWidth()

Returns the width of the viewport.

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

class method

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 fire.

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

    class method

    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.

    observe is the document-wide version of observe. Using 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');
    });
    class method

    document.on

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

    See 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.

    class method

    document.stopObserving

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

    Unregisters an event handler from the document.

    stopObserving is the document-wide version of stopObserving.

    class property

    document.loaded

      • document.loaded
        • Boolean

    Whether the full DOM tree is ready for manipulation.

    instance method

    document#on

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

    See 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.

    class

    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

    • Element.Methods

      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.

    Constructor

    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");
    class

    Element.Layout

    Description

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

    Overview

    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.

    Usage

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

    var layout = new Element.Layout(someElement);

    You can also use 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)

    Caching

    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.

    Hidden elements

    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

    constructor

    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.

    instance method

    Element.Layout#get

      • Element.Layout#get(property)
      • property
        • String
      • One of the properties defined in PROPERTIES.

    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.
    instance method

    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 setStyle.

    instance method

    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');
    instance method

    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');
    constant

    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.

    constant

    Element.Layout.PROPERTIES

      • Element.Layout.PROPERTIES

    A list of all measurable properties.

    mixin

    Element.Methods

    Description

    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();
    class

    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.

    constructor

    Element.Offset.new

      • new Element.Offset(left, top)

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

    instance method

    Element.Offset#inspect

      • Element.Offset#inspect()

    Returns a debug-friendly representation of the offset.

    instance method

    Element.Offset#relativeTo

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

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

    instance method

    Element.Offset#toArray

      • Element.Offset#toArray()

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

    instance method

    Element.Offset#toString

      • Element.Offset#toString()
    class method

    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.

    class method

    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.

    class method

    Element.addMethods

      • Element.addMethods(methods)
        • undefined
      • 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.

    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 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 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: 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 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 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).

    class method

    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.

    class method

    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.

    class method

    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, 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.

    class method

    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 addClassName, removeClassName, and 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.

    class method

    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 up, down, next, and 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.

    class method

    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, 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.

    class method

    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
    Name Default Description
    setLeft true Clones source's left CSS property onto element.
    setTop true Clones source's top CSS property onto element.
    setWidth true Clones source's width onto element.
    setHeight true Clones source's width onto element.
    offsetLeft 0 Number by which to offset element's left CSS property.
    offsetTop 0 Number by which to offset element's top CSS property.

    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.

    class method

    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.

    class method

    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.

    class method

    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.

    class method

    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.

    class method

    Element.down

      • Element.down(element[, expression][, index = 0])
      • 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 down method is part of Prototype's ultimate DOM traversal toolkit (check out up, next and 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 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 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 descendants.) Note that the first element has an index of 0.

    If expression is defined, 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, 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.

    class method

    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.

    class method

    Element.extend

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

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

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

    Details

    Specifically, extend extends the given instance with the methods contained in 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.

    class method

    Element.fire

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

    See fire.

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

    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: fire waits until the event finishes its life cycle, then returns the event itself.

    Note

    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 stop will have a boolean stopped property set to true. Since 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.

    class method

    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.

    class method

    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. 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 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.

    class method

    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.

    class method

    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 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.

    class method

    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 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.

    class method

    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.

    class method

    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.

    class method

    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.

    class method

    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 getOpacity and 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 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.

    class method

    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 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.

    class method

    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.

    class method

    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 each:

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

    Hide multiple elements using 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.

    class method

    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.

    class method

    Element.immediateDescendants

    Deprecated
      • Element.immediateDescendants(element)

    This method is deprecated, please see 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.

    class method

    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).

    Examples

    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.

    class method

    Element.inspect

      • Element.inspect(element)

    Returns the debug-oriented string representation of element.

    For more information on inspect methods, see 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.

    class method

    Element.makeClipping

      • Element.makeClipping(element)

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

    To undo clipping, use 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.

    class method

    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 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.

    class method

    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.

    class method

    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 getLayout and operate on the 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.

    class method

    Element.next

      • Element.next(element[, expression][, index = 0])
      • 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 next method is part of Prototype's ultimate DOM traversal toolkit (check out up, down and 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 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 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 nextSiblings). Note that the sibling right below element has an index of 0.

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

    If both expression and index are defined, 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.

    class method

    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.

    class method

    Element.observe

      • Element.observe(element, eventName, handler)

    See 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.

    class method

    Element.on

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

    See 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.

    class method

    Element.positionedOffset

      • Element.positionedOffset(element)

    Returns element's offset relative to its closest positioned ancestor (the element that would be returned by 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.

    class method

    Element.previous

      • Element.previous(element[, expression][, index = 0])
      • 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 previous method is part of Prototype's ultimate DOM traversal toolkit (check out up, down and 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 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 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 previousSiblings). Note that the sibling right above element has an index of 0.

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

    If both expression and index are defined, 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.

    class method

    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.

    class method

    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.

    class method

    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.

    class method

    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 ancestors, descendants, nextSiblings, previousSiblings and siblings which offer really convenient way to grab elements, so directly accessing 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.

    class method

    Element.relativize

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

    Used to undo a call to 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.

    class method

    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 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.

    class method

    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.

    class method

    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 (replace internally calls evalScripts).

    Note that if no argument is provided, replace will simply clear element of its content. However, using 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 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.

    class method

    Element.retrieve

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

    Retrieves custom metadata set on element with 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.

    class method

    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.

    class method

    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

    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 extend on each node (so that custom instance methods can be used on the nodes). 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.

    class method

    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.

    setStyle method uses 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.

    class method

    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.

    class method

    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 each:

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

    Show multiple elements using invoke:

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

    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.

    class method

    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.

    class method

    Element.stopObserving

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

    See 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.

    class method

    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 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.

    class method

    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 each:

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

    Toggle multiple elements using 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

    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.

    class method

    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.

    class method

    Element.undoClipping

      • Element.undoClipping(element)

    Sets element's CSS overflow property back to the value it had before 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.

    class method

    Element.undoPositioned

      • Element.undoPositioned(element)

    Sets element back to the state it was in before 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.

    class method

    Element.up

      • Element.up(element[, expression][, index = 0])
      • 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 up method is part of Prototype's ultimate DOM traversal toolkit (check out down, next and 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 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 ancestors). Note that the first element has an index of 0.

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

    If both expression and index are defined, 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.

    class method

    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 defer) to allow the browser to finish updating the DOM. Note that the scripts are evaluated in the scope of evalScripts, not in the global scope, which has important ramifications for your vars and functions. See 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 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.

    class method

    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.

    class method

    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.

    class method

    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, 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 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 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.

    class method

    Element.writeAttribute

      • Element.writeAttribute(element, attribute[, value = true])
      • 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.

    instance method

    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.

    instance method

    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.

    instance method

    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.

    instance method

    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.

    instance method

    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, 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.

    instance method

    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 addClassName, removeClassName, and 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.

    instance method

    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 up, down, next, and 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.

    instance method

    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, 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.

    instance method

    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
    Name Default Description
    setLeft true Clones source's left CSS property onto element.
    setTop true Clones source's top CSS property onto element.
    setWidth true Clones source's width onto element.
    setHeight true Clones source's width onto element.
    offsetLeft 0 Number by which to offset element's left CSS property.
    offsetTop 0 Number by which to offset element's top CSS property.

    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.

    instance method

    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.

    instance method

    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.

    instance method

    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.

    instance method

    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.

    instance method

    Element#down

      • Element#down([expression][, 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 down method is part of Prototype's ultimate DOM traversal toolkit (check out up, next and 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 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 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 descendants.) Note that the first element has an index of 0.

    If expression is defined, 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, 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.

    instance method

    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.

    instance method

    Element#fire

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

    See fire.

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

    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: fire waits until the event finishes its life cycle, then returns the event itself.

    Note

    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 stop will have a boolean stopped property set to true. Since 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.

    instance method

    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.

    instance method

    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. 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 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.

    instance method

    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.

    instance method

    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 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.

    instance method

    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 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.

    instance method

    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.

    instance method

    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.

    instance method

    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.

    instance method

    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 getOpacity and 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 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.

    instance method

    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 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.

    instance method

    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.

    instance method

    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 each:

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

    Hide multiple elements using 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.

    instance method

    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.

    instance method

    Element#immediateDescendants

    Deprecated
      • Element#immediateDescendants()

    This method is deprecated, please see 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.

    instance method

    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).

    Examples

    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.

    instance method

    Element#inspect

    Returns the debug-oriented string representation of element.

    For more information on inspect methods, see 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.

    instance method

    Element#makeClipping

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

    To undo clipping, use 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.

    instance method

    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 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.

    instance method

    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.

    instance method

    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 getLayout and operate on the 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.

    instance method

    Element#next

      • Element#next([expression][, 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 next method is part of Prototype's ultimate DOM traversal toolkit (check out up, down and 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 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 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 nextSiblings). Note that the sibling right below element has an index of 0.

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

    If both expression and index are defined, 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.

    instance method

    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.

    instance method

    Element#observe

      • Element#observe(eventName, handler)

    See 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.

    instance method

    Element#on

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

    See 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.

    instance method

    Element#positionedOffset

      • Element#positionedOffset()

    Returns element's offset relative to its closest positioned ancestor (the element that would be returned by 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.

    instance method

    Element#previous

      • Element#previous([expression][, index = 0])
      • 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 previous method is part of Prototype's ultimate DOM traversal toolkit (check out up, down and 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 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 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 previousSiblings). Note that the sibling right above element has an index of 0.

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

    If both expression and index are defined, 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.

    instance method

    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.

    instance method

    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.

    instance method

    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.

    instance method

    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 ancestors, descendants, nextSiblings, previousSiblings and siblings which offer really convenient way to grab elements, so directly accessing 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.

    instance method

    Element#relativize

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

    Used to undo a call to 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.

    instance method

    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 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.

    instance method

    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.

    instance method

    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 (replace internally calls evalScripts).

    Note that if no argument is provided, replace will simply clear element of its content. However, using 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 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.

    instance method

    Element#retrieve

      • Element#retrieve(key[, defaultValue])
        • ?

    Retrieves custom metadata set on element with 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.

    instance method

    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.

    instance method

    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

    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 extend on each node (so that custom instance methods can be used on the nodes). 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.

    instance method

    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.

    setStyle method uses 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.

    instance method

    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.

    instance method

    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 each:

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

    Show multiple elements using invoke:

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

    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.

    instance method

    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.

    instance method

    Element#stopObserving

      • Element#stopObserving([eventName][, handler])

    See 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.

    instance method

    Element#store

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

    The metadata can later be retrieved with 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.

    instance method

    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 each:

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

    Toggle multiple elements using 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

    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.

    instance method

    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.

    instance method

    Element#undoClipping

    Sets element's CSS overflow property back to the value it had before 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.

    instance method

    Element#undoPositioned

    Sets element back to the state it was in before 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.

    instance method

    Element#up

      • Element#up([expression][, 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 up method is part of Prototype's ultimate DOM traversal toolkit (check out down, next and 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 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 ancestors). Note that the first element has an index of 0.

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

    If both expression and index are defined, 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.

    instance method

    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 defer) to allow the browser to finish updating the DOM. Note that the scripts are evaluated in the scope of evalScripts, not in the global scope, which has important ramifications for your vars and functions. See 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 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.

    instance method

    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.

    instance method

    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.

    instance method

    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, 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 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 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.

    instance method

    Element#writeAttribute

      • Element#writeAttribute(attribute[, value = true])
      • 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.

    class

    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 observe, element and stop. If your web app uses custom events, you'll also get a lot of mileage out of 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 extend, in the same way that Element methods are added to DOM nodes through extend. Events are extended automatically when handlers are registered with Prototype's observe method; if you're using a different method of event registration, for whatever reason,you'll need to extend these events manually with 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.

    class

    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 on.

    Instance properties

    constructor

    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 start is called.

    instance property

    Event.Handler#start

    Starts listening for events. Returns itself.

    instance property

    Event.Handler#stop

    Stops listening for events. Returns itself.

    class method

    Event.element

    Deprecated
      • event
        • Event
      • An Event object

    Returns the DOM element on which the event occurred. This method is deprecated, use 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 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 element might very well not be extended. If you intend to use methods from 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.

    class method

    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 observe or 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.

    class method

    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.

    class method

    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.

      class method

      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.

      class method

      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.

      class method

      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.

      class method

      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 observe.

      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). observe makes it possible to stop observing the event easily via stopObserving. * Adds support for mouseenter / mouseleave events in all browsers.

      Although you can use observe directly and there are times when that's the most convenient or direct way, it's more common to use its alias observe. These two statements have the same effect:

      Event.observe('foo', 'click', myHandler);
      $('foo').observe('click', myHandler);

      The examples in this documentation use the 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 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 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. 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 stopObserving or its 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 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 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 bind, it works correctly. See bind for details. There's also bindAsEventListener, which is handy for certain very specific situations. (Normally, 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, 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 findElement method.

      class 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 Handler, calls 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 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 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 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.

      class method

      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.

      class method

      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.

      class method

      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.

      class method

      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.

      class method

      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 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 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

      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
      instance method

      Event#element

      Deprecated
        • event
          • Event
        • An Event object

      Returns the DOM element on which the event occurred. This method is deprecated, use 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 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 element might very well not be extended. If you intend to use methods from 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.

      instance method

      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 observe or 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.

      instance method

      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.

      instance method

      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.

      instance method

      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.

      instance method

      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.

      instance method

      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.

      instance method

      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.

      instance method

      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.

      instance method

      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.

      namespace

      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 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.EventObserver

      • Form.Observer

        An 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 serialize).

      namespace

      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 focus, serialize, disable/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

      class

      Form.Element.EventObserver

      class

      Form.Element.Observer

      Description

      An TimedObserver subclass that watches for changes to a form field's value. This triggers the callback when the form field's value (according to 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 getValue on the given element. See TimedObserver for general documentation on timed observers.

      constructor

      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 Observer.

      class method

      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.

      class method

      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.

      class method

      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.

      class method

      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.

      class method

      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()
      class method

      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:
      class method

      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.

      class method

      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 activate!

      The activate method is a nifty way to both focus a form field and select its current text, all in one portable JavaScript call.

      class method

      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 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 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.

      class method

      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.

      instance method

      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