W3C

XML Binding Language (XBL) 2.0

W3C Candidate Recommendation 16 March 2007

This Version:
http://www.w3.org/TR/2007/CR-xbl-20070316/
Latest Version:
http://www.w3.org/TR/xbl/
Previous Versions:
http://www.w3.org/TR/2007/WD-xbl-20070117/
http://www.w3.org/TR/2006/WD-xbl-20060907/
http://www.w3.org/TR/2006/WD-xbl-20060619/
http://www.mozilla.org/projects/xbl/xbl.html
http://www.w3.org/TR/2001/NOTE-xbl-20010223/
Editor:
Ian Hickson, Google, Inc.

Abstract

The XML Binding Language (XBL) describes the ability to associate elements in a document with script, event handlers, CSS, and more complex content models, which can be stored in another document. This can be used to re-order and wrap content so that, for instance, simple HTML or XHTML markup can have complex CSS styles applied without requiring that the markup be polluted with multiple semantically neutral div elements.

It can also be used to implement new DOM interfaces, and, in conjunction with other specifications, enables arbitrary tag sets to be implemented as widgets. For example, XBL could be used to implement the form controls in XForms or HTML.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This is the 16 March 2007 Candidate Recommendation of XBL 2.0. Implementations are encouraged. This specification will remain at the Candidate Recommendation stage until two complete and interoperable implementations exist (and not before 1 September 2007). An implementation will only be considered if it is publicly downloadable or available through some other public point of sale mechanism, and is intended for a wide audience and could be used on a daily basis. To be "complete and interoperable", an implementation must pass every test in a comprehensive test suite of every normative requirement of this specification.

Publication as a Candidate Recommendation does not imply endorsement by the W3C Membership. At the time of publication, there was no implementation report. A future version of this specification, which will include fixes based on implementation feedback, will include a link to a test suite and an implementation report.

If you wish to make comments regarding this document, please send them to dev-tech-xbl@mozilla.org (subscribe, archives) or public-appformats@w3.org (subscribe, archives). All feedback is welcome. The editor guarantees that all feedback sent to the above lists will receive responses before this specification advances to the next stage of the W3C process.

The editor's copy of this specification is available in W3C CVS. A detailed list of changes is available from the CVS server.

This specification is a (non-backwards-compatible) revision of Mozilla's XBL 1.0 language, originally developed at Netscape in 2000, and originally implemented in the Gecko rendering engine. [XBL10]

This specification was developed by the Mozilla Foundation and its contributors, in conjunction with individuals from Opera Software ASA, Google, Inc, and Apple Computer, Inc, to address problems found in the original language and to allow for implementation in a broader range of Web browsers.

This document is also based, in part, on work done in the W3C's Bindings Task Force. However, no text from that collaboration, other than that written by the aforementioned contributors, remains in this specification. Inspiration was similarly taken from other efforts, such as HTML Components. [HTC]

Although they have had related histories, this specification is separate from the W3C's "sXBL" drafts, and is not compatible with them. (The two efforts use different namespaces, for one.)

While the body of this specification was created outside the W3C, the W3C Web Application Formats Working Group is now guiding this specification along the W3C Recommendation track.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

Feedback requests

While feedback is welcomed on all aspects of this specification, especially from implementors and authors using XBL on the Web, feedback is especially requested on two contentious issues.

The first concerns ID attributes. This specification defines an attribute id for uniquely identifying elements in XBL. There exists a specification for a global xml:id attribute, which can also be used with XBL. Feedback is requested from implementors and authors using XBL on the Web regarding whether XBL should instead require that authors use the xml:id attribute, and forbid the use of the id attribute on XBL elements.

The second contentious issue regards an intentional limitation: unless an element is explicitly bound to a binding that provides access to its shadow tree or its bound element, there is no easy way to get access to them from script running outside the element's bindings. This is a feature that may be introduced in a future version, but it is not clear how much need there is for it.

If you have any opinions or experience regarding these issues or any others, please send them to dev-tech-xbl@mozilla.org (subscribe, archives) or public-appformats@w3.org (subscribe, archives).

Table of Contents


1. Introduction

This specification defines the XML Binding Language and some supporting DOM interfaces and CSS features. XBL is a mechanism for overriding the standard presentation and interactive behavior of particular elements by attaching those elements to appropriate definitions, called bindings. Bindings can be attached to elements using either CSS, the DOM, or by declaring, in XBL, that elements matching a specific selector are implemented by a particular binding. The element that the binding is attached to, called the bound element, acquires the new behavior and presentation specified by the binding.

Bindings can contain event handlers that watch for events on the bound element, an implementation of new methods and properties that become accessible from the bound element, shadow content that is inserted underneath the bound element, and associated resources such as scoped style sheets and precached images, sounds, or videos.

XBL cannot be used to give a document new semantics. The meaning of a document is not changed by any bindings that are associated with it, only its presentation and interactive behavior.

To help readers understand how certain features can be used, this specification includes some examples.

In these examples, a long ellipsis ("...") is used to indicate elided content that would be present in a full example but has been removed for clarity.

Here we see a simple binding being used to reorder content in an HTML page, so that the element with class="nav" is positioned before the element with class="main". CSS associated with the binding is then used to position the two elements.

<xbl xmlns="http://www.w3.org/ns/xbl">
 <binding id="nav-then-main">
  <template>
   <div id="wrapper">
    <div id="col2"><content includes=".nav"/></div>
    <div id="col1"><content includes=".main"/></div>
   </div>
  </template>
  <resources>
   <style>
    #wrapper { display: table-row; }
    #col1, #col2 { display: table-cell; }
   </style>
  </resources>
 </binding>
</xbl>

The HTML page associated with such a binding might look like:

<!DOCTYPE HTML>
<html>
 <head>
  <title>Demo</title>
  <link rel="stylesheet" href="example.css">
 </head>
 <body>
  <div class="main">
   <h1>Demo</h1>
   ...
  </div>
  <div class="nav">
   <p><a href="http://example.com/">Home</a></p>
   ...
  </div>
 </body>
</html>

The CSS stylesheet referred to from that document would include various stylistic rules, and would in particular contain a link to the XBL file, making it apply to the body element so as to reorder the two child elements:

/* Colors and Fonts */
h1 { font: 2em sans-serif; color: green; background: white; }
...

/* Reorder content */
body { binding: url(example.xml#nav-then-main); }

The result of all the above is equivalent to the result one would get if one simply placed the div element with class="nav" before the div element with class="main". However, the effect is achieved without needing any changes to the markup. This allows the same markup to be given different presentations dynamically. It also allows changes to be applied across entire sites by merely changing global stylesheet and binding files, much as CSS can be used to change the layout and presentation of a site even without XBL.

Here is another example, this time of an inaccessible implementation of the proposed HTML5 details disclosure element: it opens and closes when clicked, and reflects its current state in the element's "open" attribute.

<xbl xmlns="http://www.w3.org/ns/xbl">
 <binding element="details">
  <template>
   <div>
    <div><content includes="legend:first-child">Details...</content></div>
    <div state="hidden" id="container"><content/></div>
   </div>
  </template>
  <handlers>
   <handler event="click" phase="default-action">
    this.open = !this.open;
   </handler>
   <handler event="DOMAttrModified" attr-name="open" attr-change="addition" phase="target">
    this.shadowTree.getElementById('container').setAttribute('state', 'visible');
   </handler>
   <handler event="DOMAttrModified" attr-name="open" attr-change="removal" phase="target">
    this.shadowTree.getElementById('container').setAttribute('state', 'hidden');
   </handler>
  </handlers>
  <implementation>
   ({
     get open() { return this.boundElement.hasAttribute('open'); },
     set open(val) {
       if (val)
         this.boundElement.setAttribute('open', 'open');
       else
         this.boundElement.removeAttribute('open');
       return this.open;
     },
   })
  </implementation>
  <resources>
   <style>
    #container[state=hidden] { display: none; }
   </style>
  </resources>
 </binding>
</xbl>

Since the examples are all untested (there are no XBL2 implementations at the time of writing), it is quite possible that they have errors. Please report any errors you think you see, so that we can correct the examples.

1.1. Relationship to XBL1

This specification is not backwards compatible with XBL1.

There are numerous changes. However, of particular importance to readers familiar with XBL1, there have been some changes to the element names. In particular, the XBL1 element content is now called template, and the XBL1 element children is now called content.

1.2. Relationship to XSLT

This specification has a similar scope to XSLT. The main differences are:

In addition, XBL can be used for component creation, which is not covered by XSLT.

1.3. Terminology and Conventions

An XBL user agent is an implementation that attempts to support this specification.

A binding is the definition of behavior that can be applied to an element so as to augment its presentation.

The namespace of all the XBL elements and XBL global attributes must be: http://www.w3.org/ns/xbl

An XBL document is an XML document that has the xbl element at its root.

A non-XBL document is an XML document whose root element is from a namespace other than XBL (e.g. XHTML). A non-XBL document can include XBL, if the other languages involved allow it.

An XBL subtree is a subtree in an XML document, the subtree having as its root node an xbl element in the XBL namespace, which is used to define bindings. XBL subtrees can stand alone in XBL documents, or can be included in non-XBL documents.

The term binding document is used to mean either an XBL document or a non-XBL document containing one or more XBL subtrees.

In the following XHTML example, the XBL subtree is the portion of the markup that is emphasized. It is in a non-XBL document, since the root element is an XHTML element.

<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title>Demo</title>
  <xbl xmlns="http://www.w3.org/ns/xbl">
   <script><![CDATA[
     function fmt(n) {
       if (n < 10)
         return "0" + n;
       else
         return n;
     }
   ]]></script>
   <binding element=".date">
    <implementation>
      ({
        xblBindingAttached: function() {
          var tm = /(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d) UTC$/.exec(this.boundElement.textContent);
          var date = new Date();
          date.setUTCFullYear(parseInt(tm[1], 10));
          date.setUTCMonth(parseInt(tm[2], 10) - 1);
          date.setUTCDate(parseInt(tm[3], 10));
          date.setUTCHours(parseInt(tm[4], 10));
          date.setUTCMinutes(parseInt(tm[5], 10));
          date.setUTCSeconds(0);
          this.boundElement.textContent = date.getFullYear() + "-" +
                                      fmt(date.getMonth() + 1) + "-" +
                                      fmt(date.getDate()) + " " +
                                      fmt(date.getHours()) + ":" +
                                      fmt(date.getMinutes()) + " LT";
          this.boundElement.title = "Adjusted to local time zone"
        },
      })
    </implementation>
   </binding>
  </xbl>
 </head>
 <body>
  <h1>Demo</h1>
  <p class="date">2006-08-10 18:40 UTC</p>
  <p>...</p>
 </body>
</html>

(As an aside, the binding defined in this example causes elements with class="date" to have their content parsed into a UTC date and converted into a local time. The binding mutates the original DOM to do this, and it doesn't reflect any dynamic changes made to the element's content; there are better, albeit slightly more involved, ways of achieving the same effect that don't have these problems.)

A bound element is an XML or HTML element to which a binding has been applied.

In the example above, the first p element is the bound element.

A bound document is an XML or HTML document containing one or more bound elements.

In the example at the top of this section, the document is both the binding document (because it contains the definition of the binding), and the bound document (because it contains the affected bound element). In the example in the introduction section, the HTML file is the bound document, and the XBL file is the binding document.

In this specification, the term in error, typically used of an element or attribute, means that the element, attribute, or other construct is not conformant according to the rules of this specification. Rules for exactly how the construct must be treated when it is in error are always given when the term is used. Typically this will involve ignoring the erroneous nodes, meaning the UA must, for the purposes of XBL processing, act as if those nodes were absent. UAs must not, however, remove such nodes from the DOM in order to ignore them, nor should it change what DOM interfaces those nodes implement. The nodes retain all their non-XBL semantics.

UAs should report all errors to users, although they may do this in an unobtrusive way, for example in an error console.

In addition to the error handling rules given in this specification, UAs may abort all processing when encountering an error.

Aborting is only likely to be a viable error handling mechanism in controlled environments, e.g. in conformance checkers. Web browsers are expected to use the error recovery mechanisms described in this specification, not abort.

A correct element, attribute, value, or binding is one which is not in error.

The following sample XBL document is in error because the script element in XBL is only allowed as a child of the xbl element:

<xbl xmlns="http://www.w3.org/ns/xbl">
 <binding id="demo">
  <script>
   // This example is in error.
   // You are not allowed to put a script element inside
   // a binding element, only inside an xbl element.
   // This is because scripts evaluate in the scope of the
   // entire XBL document, and are therefore not associated
   // with a particular binding.
   function life() {
     return 42;
   }
  </script>
 </binding>
</xbl>

The correct way of doing this would be:

<xbl xmlns="http://www.w3.org/ns/xbl">
 <script>
  // This example is correct.
  function life() {
    return 42;
  }
 </script>
 <binding id="demo">
  <!-- Now you can see that this binding actually does nothing. -->
 </binding>
</xbl>

The term "semantics" is used to refer to the intrinsic meaning or processing model of elements, attributes, events, and DOM interface members. Semantics are defined by specifications; for example, this specification defines the semantics of XBL elements.

XBL elements are frequently referred to by just their local name in this specification. In real documents, they must be associated with the XBL namespace as per the rules given in the Namespaces in XML specification [XMLNS].

For convenience, elements and attributes from specific namespaces are sometimes referred to simply in the form prefix:localname, without explicitly stating which namespace the prefix is bound to. When this occurs, readers should assume the following prefix declarations are in scope:

xmlns:xbl="http://www.w3.org/ns/xbl"
xmlns:xforms="http://www.w3.org/2002/xforms"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:html="http://www.w3.org/1999/xhtml"

When this specification refers to elements in a namespace, it does not exclude elements in no namespace; the null namespace is considered a namespace like any other for the purposes of XBL processing.

All element names, attribute names, and attribute values in XBL are case sensitive, with the exception of attribute values defined by other specifications (those have the sensitivity defined by those other specifications).

An XML MIME type is text/xml, application/xml, or any MIME type ending with the string +xml (ignoring any MIME parameters).

The terms "author style sheets", "user style sheets", "user agent style sheets", and "pseudo-element" are used as defined by the CSS specifications. [CSS21]

The term "QName" is used as defined by the Namespaces in XML specification. [XMLNS]

The term "view" is used as defined by the DOM2 Views specification. [DOM2VIEWS]

1.4. Conformance

As well as sections marked as non-normative, all diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in the normative parts of this document are to be interpreted as described in RFC2119. For readability, these words do not appear in all uppercase letters in this specification. [RFC2119]

There are two classes of products that can claim conformance to this implementation: XBL subtrees, and XBL user agents.

XBL subtrees must satisfy the constraints described in this specification in order to be considered conformant.

Products that generate XBL subtrees cannot claim conformance to this specification, though they can claim to only produce XBL subtrees that themselves are conformant to this specification.

XBL user agents must behave as described by this specification in order to be considered conformant, even when faced with non-conformant XBL subtrees.

User agents may optimize any algorithm given in this specification, so long as the end result is indistinguishable from the result that would be obtained by the specification's algorithms. (The algorithms in this specification are generally written with more concern for clarity than over efficiency.)

This specification is defined in terms of the DOM. The language in this specification assumes that the user agent expands all entity references, and therefore does not include entity reference nodes in the DOM. If user agents do include entity reference nodes in the DOM, then user agents must handle them as if they were replaced by their DOM replacement values when implementing this specification.

For example, if a requirement talks about an element's child text nodes, then any text nodes that are children of an entity reference that is a child of that element would be used as well.

1.4.1. Error Handling

This specification describes the rules for processing of XBL elements and related features, whether they are used in a conformant manner or not. Conformant implementations, therefore, will interoperably handle any content, whether valid or not.

1.4.2. Attributes Containing Selectors

The element attribute of the binding element and the includes attribute of the content element, if specified, must have their values parsed according to the rules in the Selectors specification. [SELECTORS]

This specification does not specify what level of Selectors support is required.

Namespace prefixes can be used with selectors. In XBL attributes that take selectors, the namespace prefixes that may be used are the prefixes that are in scope using the xmlns:* syntax. User agents must use the XML namespace prefixes in scope on the attribute's element when parsing selectors with namespace prefixes. The default namespace in selectors in XBL attributes is always unbound. [XMLNS]

The "xml" prefix is defined to always be declared (and bound to the http://www.w3.org/XML/1998/namespace namespace), as is the "xmlns" prefix (which is bound to http://www.w3.org/2000/xmlns/).

Selectors are case-insensitive, but namespace prefixes are case-sensitive. Thus, there could be multiple namespace prefixes declared that match a particular namespace prefix as used in a selector. User agents must act as if all namespace prefixes in scope were lexically sorted by Unicode codepoint, with the first namespace prefix of each group of namespace prefixes differing only by case (using case folding as defined by Unicode) being the one assumed to be in scope for the purposes of selector matching. [UNICODE]

The following excerpt from an XBL document defines a binding that is bound to elements declaring links (e.g. the a element in HTML).

<xbl xmlns="http://www.w3.org/ns/xbl">
 <binding element=":link, :visited">
  ...
 </binding>
</xbl>

The following excerpt defines a binding bound to any element in the http://example.com/ namespace that is the child of an element in the http://www.example.net/ namespace with the name parent. (Note that the > character does not have to be escaped.)

<xbl xmlns="http://www.w3.org/ns/xbl"
     xmlns:eg1="http://www.example.net/"
     xmlns:eg2="http://example.com/">
 <binding element="eg1|parent > eg2|*">
  ...
 </binding>
</xbl>

Finally this third example defines a binding that matches elements with the name blockquote, regardless of what namespace they are in. If it is known that the binding document is only ever going to be used from documents that use one namespace, for example if the bindings are always to be imported into HTML documents, then it is easier to just specify the local name (as in this example) and ignore the namespaces.

<xbl xmlns="http://www.w3.org/ns/xbl">
 <binding element="blockquote">
  ...
 </binding>
</xbl>

1.4.3. Attributes Containing Space-Separated Values

Some attributes are defined as taking space-separated values. The list of values for such attributes must be obtained by taking the attribute's value, replacing any sequences of U+0009, U+000A, U+000D, and U+0020 characters (in any order) with a single U+0020 SPACE character, dropping any leading or trailing U+0020 SPACE character, and then chopping the resulting string at each occurrence of a U+0020 character, dropping that character in the process.

A space-separated attribute whose value is the empty string, or which consists of only U+0009, U+000A, U+000D, and U+0020 characters, has no values.

In the attribute button="1 2", the values are "1" and "2".

In the attribute class="  key - note - rocks", there are five keywords: "key", "note", "rocks", and two occurrences of the single-character keyword "-".

1.4.4. Attributes Containing MIME Types

Some attributes are defined as containing MIME types. A valid MIME type is one that matches the production for valid-MIME-type in the following EBNF:

valid-MIME-type := type "/" subtype *(";" parameter)

...where the type, subtype, and parameter tokens are those defined in RFC 2045. [RFC2045]

1.4.5. Attributes Containing URIs

Some attributes, pseudo-attributes, and method arguments are defined as specifying URIs. Such attributes must have values that match the URI token of RFC 3986 or the IRI token of RFC 3987. If they do not, they are in error (though the processing of erroneous URIs varies depending on the context). [RFC3986] [RFC3987]

1.4.6. Attributes Containing Keywords

Certain attributes are defined as requiring certain values, e.g. true or false. For such attributes, the values must be specified exactly, in the case given in this specification, and with no leading or trailing whitespace. Implementations must only perform literal comparisons, and must not use case-insensitive comparisons nor trim attribute values before comparison.

1.4.7. Extension Mechanisms

XBL2 does not have an extension mechanism; implementations that recognize elements in the XBL namespace that aren't part of this specification, or who recognise attributes that have no namespace, that are on elements in the XBL namespace, and that aren't part of this specification, are non-conforming. If UAs support features in other namespaces that affect the XBL processing model in a way that contradicts this specification, then they are not conforming either.

1.4.8. Feature Strings for the DOM and SVG

XBL2 user agents must recognize the string "XBL" as being a DOM feature corresponding to support of XBL2 and its corresponding DOM APIs. Support for this specification must be treated as support for versions "1.0" and "2.0" of the "XBL" feature in terms of versions for the hasFeature() DOM Core method.

XBL2 user agents that also implement SVG must recognize the following string as being a language extension URI for the purposes of SVG requiredExtensions evaluation: http://www.w3.org/ns/xbl#v2

1.5. Security Concerns

This section is non-normative.

XBL raises a number of security concerns.

Data theft: A naïve implementation of XBL would allow any document to bind to bindings defined in any other document, and (since referencing a binding allows full access to that binding document's DOM) thereby allow access to any remote file, including those on intranet sites or on authenticated extranet sites.

XBL itself does not do anything to prevent this. However, it is strongly suggested that an access control mechanism (such as that described in [ACCESSCONTROL]) be used to prevent such cross-domain accesses unless the remote site has allowed accesses.

Privilege escalation: In conjunction with data theft, there is the concern that a page could bind to a binding document on a remote site, and then use the privileges of that site to obtain further information. XBL prevents this by requiring that the bindings all run in the security context of the bound document, so that accessing a remote binding document does not provide the bound document with any extra privileges on the remote domain.

Cookie theft: Related to privilege escalation is the risk that once an access-controlled binding document hosted on a remote site has been loaded, authentication information stored in cookies for that domain would become accessible to the bound document. XBL prevents this by requiring that the cookie attribute on the DocumentWindow interface be set to null.

Secure bindings: Using XBL for bindings that need access to the local filesystem, e.g. for implementing File Upload form controls, is not yet handled by this specification. However, a future version will provide a secure way to define an XBL binding that can be used to implement privileged mechanisms that can then be used by other bindings to provide such controls.

2. XBL Elements

The start of any XBL subtree is an xbl element, which is described below.

When an XBL element is found inside an element other than those listed under the "Expected contexts" list in the definitions below, it is in error. When an XBL element has a child node that does not satisfy the "Expected children" list in its definition (for instance because it is the wrong node type, wrong element type, or because too many elements of its type preceded it), the child is in error. In both cases, being in error means that the UA must, for the purposes of XBL evaluation, treat the XBL subtree as it would if the erroneous node and all its descendants were not present in the DOM.

However, non-XBL elements retain their semantics, even when considered to be in error for the purposes of XBL.

Regardless of the requirements of the last few paragraphs and of the "expected children" lines, comment nodes, and text and CDATA nodes containing only whitespace characters, may always be given as children of XBL elements.

For cases where attributes on XBL elements do not conform to this specification or (for namespaced attributes) to another specification, and for cases where attributes in the XBL namespace are found on elements other than those listed as their "Expected element" in the definitions below, the error handling is similar: the attributes must be considered to be in error and the UA must ignore them, meaning that the presence of these non-conforming attributes in no way affects the XBL processing.

Further error handling rules for more specific cases are given where appropriate.

XBL user agents that support CSS should act as if they had the following rules in their UA style sheet:

@namespace xbl url(http://www.w3.org/ns/xbl);
xbl|* { display: none; }
xbl|div { display: block; }

XBL user agents that do not support CSS should not render the XBL elements other than the div element, which they should render as a paragraph-like element.

The following sections describe the content model of XBL elements, but not their actual processing model. The processing model for XBL is described in later sections.

2.1. The xbl Element

Expected contexts:
In an XBL document, none (this is the root element).
In a non-XBL document, any non-XBL element whose specification allows the xbl element as a child.
Expected children (in any order):
binding: zero or more.
script: zero or more.
Any non-XBL element.

The xbl element is the root element of all XBL subtrees.

Attributes

id
The id attribute.
script-type
The script-type attribute specifies the MIME type of the scripting language used by all bindings and XBL script blocks in the XBL subtree. The value must be a valid MIME type. If the attribute is not specified, the default language is ECMAScript. [ECMA262]
style-type
The style-type attribute specifies the MIME type of the styling language used by all bindings and XBL style blocks in the XBL subtree. The value must be a valid MIME type. If the attribute is not specified, the default language is CSS (text/css).

UAs must consider any xbl elements that have another xbl element as an ancestor as being in error and must then ignore them, meaning those elements must never be considered to declare any bindings.

For example, conforming UAs will never bind elements to bindings defined by binding elements that have two xbl ancestors.

Similarly, XBL elements (other than the xbl element itself) that do not have a correct xbl element as an ancestor are in error too, and UAs must ignore them.

For example, conformant UAs will never bind elements to bindings defined by binding elements that have no xbl ancestors at all.

The same does not apply to the style-type and script-type attributes. If the UA does not support the specified styling language (or has styling disabled), it must still apply bindings as appropriate; only style blocks must be ignored. Similarly, if the UA does not support the specified scripting language (or has scripting disabled), it must still apply bindings as appropriate; only script, handler and implementation sections must be ignored.

The empty string is not a special value for these attributes. Setting the style-type attribute to the empty string, e.g., will result in all style blocks being ignored, since the empty string is not a valid MIME type that the UA supports.

The following document defines two bindings, one using Perl as the scripting language and the other using JavaScript. The second one extends the first one. (This example assumes that text/x-perl refers to Perl. Note that this specification doesn't actually define how Perl-based bindings are to be supported by the UA; the code below assumes that an implementation element takes an anonymous Perl package and blesses a hash to that package for each binding, but this is nothing but conjecture.)

<root>
 <xbl xmlns="http://www.w3.org/ns/xbl"
      script-type="text/x-perl">
  <binding id="validityImplementor">
   <implementation>
    use strict;
    use vars qw(@ISA);
    @ISA = qw(XBLImplementation);
    sub validate {
      my $self = shift;
      my $data = $self->{boundElement}->getAttribute('value');
      my $pattern = $self->{boundElement}->getAttribute('pattern');
      return $data =~ m/^(?:$pattern)$/s;
    }
   </implementation>
  </binding>
 </xbl>
 <xbl xmlns="http://www.w3.org/ns/xbl">
  <binding id="validityClassifier" extends="#validityImplementor">
   <handlers>
    <handler event="change">
     if (this.baseBinding.validate())
       this.boundElement.className = 'valid';
     else
       this.boundElement.className = 'invalid';
    </handler>
   </handlers>
  </binding>
 </xbl>
</root>

(What these bindings do is somewhat boring. The first does nothing except expose a "validate()" method that returns true if the contents of the element's value attribute matches the regular expression in the element's pattern attribute. The second makes the binding call this method every time the change event bubbles through the element, and changes the element's class attribute based on the return value.)

2.2. The binding Element

Expected context:
xbl
Expected children (in any order):
implementation: zero or one.
template: zero or one.
handlers: zero or one.
resources: zero or one.
Any non-XBL element

The binding element describes a single XBL binding that adds presentation and interactive behavior to XML or HTML elements. Each binding has these optional components:

Methods, Properties, and Fields: A binding can specify additional methods that can be invoked on the element. It can also specify additional properties and fields that can be retrieved or set on the element. In this way the functionality of the bound element becomes extensible. (See: binding implementations.)

Template: The optional template defines the initial shadow content for the bound element.

Behavior: A binding can define event listeners for various types of events. Some examples are: UI events (e.g., key and mouse events) on the bound element or on elements within the shadow content, and mutation events on the bound element and its descendants. (See: event handlers.)

Resources: A binding can list style sheets that are scoped to the bound element, and images, sounds, videos, or other files that a user agent can pre-cache in order to improve performance. (See: binding style sheets, prefetching resources.)

Bindings can act as an attachment mechanism, specifying a namespace and local name of elements to associate with the given binding when the binding is imported, using the element attribute.

In addition to the above, the binding element's child nodes may include any element outside the XBL namespace. These are handled as they would be in any other context, and are ignored by the XBL processing model.

Attributes

id
The id attribute.
extends
The extends attribute is used to specify the URI of a binding that this binding inherits from. (See: interpretation of URIs to XBL bindings.) If the URI is in error or does not refer to another binding, the UA must ignore it, meaning that this binding does not explicitly inherit from another binding. (See: explicit inheritance.) Only one URI can be specified.
element

This attribute, if specified, must contain a selector. All elements in the binding document, and in any documents that import the binding document, that match the given selector, must be bound to the binding defined by this binding element. (The element's own shadow tree, if any, must not be taken into account when determining if it matches a selector for the purposes of this attribute.)

If an element attribute contains an invalid selector, it is in error and must be ignored, meaning that while the binding is still parsed and may be referenced using other attachment mechanisms, the binding is not attached to any element by its element attribute, as if the attribute had simply been omitted.

The binding element defines a presentation and behavior binding. It does not define an element's semantics. If an element has no semantics when processed alone, then it has no semantics when processed with XBL.

Sending markup that does not have well-defined semantics over the network is bad practice. XBL is intended to be used to augment the user experience, for instance by providing better quality widgets or enhancing aesthetics. If the document being sent is unusable without XBL, then XBL is being abused.

This binding extends a binding defined in an external file. The binding in the other file defines a value property, and fires events when that property is changed. This binding just implements a check box that all checkbox elements in the http://ui.example.com/ namespace will be bound to.

<xbl xmlns="http://www.w3.org/ns/xbl"
     xmlns:ui="http://ui.example.com/">
 <binding element="ui|checkbox" id="checkbox"
          extends="http://www.example.org/resources/ui-core.xml#valuedControl">
  <template>
   <div id="wrapper">
    <div id="control"/>
    <div id="label"><content/></div>
   </div>
  </template>
  <resources>
   <style>
    #wrapper > div { display: inline-block; }
   </style>
  </resources>
  <handlers>
   <handler event="click" phase="default-action">
    if (this.baseBinding.value == 'on')
      this.baseBinding.value = 'off';
    else
      this.baseBinding.value = 'on';
   </handler>
   <handler event="change" phase="target">
    if (this.baseBinding.value == 'on')
      this.shadowTree.getElementById('control').textContent = '☑';
    else
      this.shadowTree.getElementById('control').textContent = '☐';
   </handler>
  </handlers>
 </binding>
</xbl>

2.3. The implementation Element

Expected context:
binding
Expected children:
If the element has no src attribute: depends on the scripting language.
If the element does have a src attribute: none.

The implementation element describes a set of methods, properties, and fields that are attached to the bound element. Once the binding is attached, these methods, properties, and fields can be invoked directly from the bound element.

The implementation element, if present, must either contain code in the language specified by the XBL subtree's script-type attribute, or have a src attribute that points to a resource containing code in the language specified by the script-type attribute. The syntax and semantics of this code depend on the specific language. This specification defines the semantics for ECMAScript implementations. (See: binding implementations.)

Attributes

id
The id attribute.
src
The src attribute specifies the URI to a resource of the type given by the XBL subtree's script-type attribute. If the attribute is specified, the contents of the element must be ignored (even if the resource could not be fetched or was of the wrong type). (See: binding implementations.)

If an implementation element is marked (via the script-type attribute of the xbl element) as being in a language that the UA does not support, then the UA must ignore it. Similarly, if the implementation element points (using the src attribute) to a resource that is either unavailable, or not of the type specified by the script-type attribute of the xbl element (or implied by its absence), then it is in error and the UA must ignore it. In both cases, "ignoring it" means it must not be used as an implementation definition for any binding.

How UAs must handle nodes inside implementation elements depends on the language used. (See: loading and running scripts, binding implementations.)

implementation blocks are evaluated once, on first use. Changes to an implementation element or its contents have no effect once the element has been evaluated. (See: binding implementations.)

The following example shows a binding that defines a new method, two new properties (one with a custom getter and setter, one without), an internal field (used to back the property), and some hooks to initialize the binding and to handle the bound element being inserted and removed from the document. The binding applies to any element with the class "demo" (in the files into which it is imported, that is).

<xbl xmlns="http://www.w3.org/ns/xbl">
 <binding element=".demo">
  <implementation>
   ({
      add: function (op1, op2) {
        return op1+op2;
      },
      get memory() {
        return this._memory.toString();
      },
      set memory(value) {
        this._memory = parseInt(value, 10);
      },
      xblBindingAttached: function() {
        this._memory = 0; // internal property to back "memory" external property
        this.external.state = 'initialized'; // external property
      },
      xblEnteredDocument: function() {
        this.external.state = 'in document';
      },
      xblLeftDocument: function() {
        this.external.state = 'out of document';
      },
   })
  </implementation>
 </binding>
</xbl>

The get field() {} and set field(syntax) {} features are part of JavaScript 1.5 and will probably be in ECMAScript 4. The examples in this specification assume an implementation that supports ECMAScript 4, but any language could be supported in real implementations.

The following example shows how to refer to an external file for the implementation of a binding. In this example, the handlers simply defer to methods defined in that implementation, so that all the code is in that file.

<xbl xmlns="http://www.w3.org/ns/xbl">
 <binding id="demo">
  <implementation src="demo.js"/>
  <handlers>
   <handler event="click"> this.clicked(event); </handler>
   <handler event="focus"> this.focused(event); </handler>
   <handler event="blur">  this.blurred(event); </handler>
  </handlers>
 </binding>
</xbl>

The demo.js file for this might look like this, to ensure that the methods defined are in fact internal methods, not exposed on the external object:

({
  xblBindingAttached: function () {
    this.clicked = function (event) { ... };
    this.focused = function (event) { ... };
    this.blurred = function (event) { ... };
  },
  // ... other methods and fields ...
})

2.4. The template Element

Expected context:
binding
Expected children:
Anything. Of particular interest, the content and inherited elements may occur as descendants, and non-XBL descendant elements may host xbl:attr and xbl:pseudo attributes.

The template element contains child nodes that can be in any namespace. When a binding is attached, the template element's child nodes are cloned and attached to the bound document under the bound element. Dynamic changes to the descendants of template elements are reflected in bindings. (See: shadow content.)

Attributes

id
The id attribute.
apply-author-sheets
The apply-author-sheets attribute indicates whether or not rules in author style sheets associated with the bound element's document apply to the shadow content generated by the binding. Its value must be either true (indicating that they do) or false (indicating that they do not). The default behavior, which is used when the attribute is omitted or has a value other than the two allowed values, is to not apply the bound document's author style sheets (same as false). (See: binding style sheets.)
allow-selectors-through
The allow-selectors-through attribute indicates whether or not rules in CSS can cross scopes. Its value must be either true (indicating that they can) or false (indicating that they cannot). The default behavior, which is used when the attribute is omitted or has a value other than the two allowed values, is to not let selectors cross scopes (same as false). (See: selectors and shadow scopes.)

The semantics of non-XBL elements inside this element are untouched, which can lead to unintuitive results. (See: semantics of non-XBL elements in XBL contexts.)

The following binding defines a shadow tree that wraps the contents of the bound element in four blocks. It uses the apply-author-sheets attribute to allow the bound document to style the nodes directly, and uses the allow-selectors-through attribute to allow the bound document to pretend (for the purposes of selector matching) that the shadow tree actually is descended from the bound element.

<xbl xmlns="http://www.w3.org/ns/xbl">
 <binding id="wrapBy4">
  <template apply-author-sheets="true" allow-selectors-through="true">
   <div class="wrap1">
    <div class="wrap2">
     <div class="wrap3">
      <div class="wrap4">
       <content/>
      </div>
     </div>
    </div>
   </div>
  </template>
 </binding>
</xbl>

Using this binding could take the following document:

<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title>Pretty Title</title>
  <style>
   h1 span { display: block; }
   h1 { border: solid red; }
   h1 .wrap1 { border: solid orange; }
   h1 .wrap2 { border: solid yellow; }
   h1 .wrap3 { border: solid green; }
   h1 .wrap4 { border: solid blue; }
  </style>
 </head>
 <body>
  <h1>
   <span class="wrap1">
    <span class="wrap2">
     <span class="wrap3">
      <span class="wrap4">
       Pretty Title
      </span>
     </span>
    </span>
   </span>
  </h1>
  ...
 </body>
</html>

...and shrink it to this:

<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title>Pretty Title</title>
  <style>
   h1 { binding: url(cool.xml#wrapBy4); }
   h1 { border: solid red; }
   h1 .wrap1 { border: solid orange; }
   h1 .wrap2 { border: solid yellow; }
   h1 .wrap3 { border: solid green; }
   h1 .wrap4 { border: solid blue; }
  </style>
 </head>
 <body>
  <h1>Pretty Title</h1>
  ...
 </body>
</html>

...which removes the semantic-free elements used as presentation hooks from the content markup layer, and places them in the presentation layer where they belong.

2.5. The content Element

Expected context:
Any, but there must be a correct template element somewhere in the ancestor chain, and there must not be any content elements anywhere in the ancestor chain.
Expected children:
Anything.

The content element is used inside shadow content to specify where explicit children that might already exist underneath the bound element are inserted into the shadow tree. As far as the presentation model is concerned, any shadow content the binding places between the bound element and the content elements is interleaved between the bound element and its explicit children without affecting the document model.

If the includes attribute has children of the bound element assigned to it, then those children are inserted into the final flattened tree in place of the content element. Otherwise, the child elements of the content element are inserted into the final flattened tree in place of the content element instead. (See: processing content elements.)

Attributes

id
The id attribute.
includes
The includes attribute can be used to indicate that only certain content should be placed at the content element. Its value must be a valid selector. (See: processing content elements.)
apply-binding-sheets
The apply-binding-sheets attribute indicates whether or not scoped style sheets loaded for an XBL binding are applied to a bound element's explicit children (in addition to the bound element itself) that are inserted below this content element when it is processed. Its value must be either true (indicating that they are) or false (indicating that they are not). The default behavior, which is used when the attribute is omitted or has a value other than the two allowed values, is that they are not applied (same as false). (See: binding style sheets.)
locked
The locked attribute indicates whether or not new children may be inserted below this content element when it is processed. Its value must be either true (indicating that they may not) or false (indicating that they may). The default behavior, which is used when the attribute is omitted or has a value other than the two allowed values, is that they may be inserted (same as false). Elements already assigned to a content element whose locked attribute is dynamically changed are not removed from that element. (See: processing content elements.)

This sample extract from a binding document shows how to use the includes attribute to distribute children to different parts of a shadow content template.

<xbl:xbl xmlns:xbl="http://www.w3.org/ns/xbl"
         xmlns:data="http://example.com/data-language">
 <xbl:binding element="data|grid">
  <xbl:template>
   <xbl:div class="caption" xbl:attr="xbl:text=title"/>
   <xbl:div class="outer-table">
    <xbl:div class="columns">
     <xbl:content includes="data|column">
      <!-- default to have just one column if none are declared -->
      <data:column/>
     </xbl:content>
    </xbl:div>
    <xbl:div class="rows">
     <xbl:content includes="data|heading"/>
     <xbl:div class="body">
      <xbl:content includes="data|row:not([hidden])"/>
     </xbl:div>
    </xbl:div>
   </xbl:div>
  </xbl:template>
  ...
 </xbl:binding>
 ...
</xbl:xbl>

The above template would be used with markup such as the following:

<data xmlns="http://example.com/data-language">
 ...
  <grid title="The Lesser of Two Evils">
   <column id="product" sort="alphabetic primary"/>
   <column id="catchphrase" sort="alphabetic secondary"/>
   <heading>
    <item>Product</item>
    <item>Catchphrase</item>
   </heading>
   <row>
    <item>Arachno Spores</item>
    <item>The fatal spore with the funny name</item>
   </row>
   <row>
    <item>Pastorama</item>
    <item>Located on the former site of Brooklyn</item>
   </row>
  </grid>
 ...
</data>

The following illustrates how the above markup would get redistributed.

The two column elements would get put under the div with
     class columns; the heading element and its descendants would end up at
     the start of the div with class rows, and the two row elements would end
     up under the div with class rows.

In this example, the binding uses the apply-binding-sheets attribute to let its stylesheet affect the explicit children of the bound element.

<xbl xmlns="http://www.w3.org/ns/xbl"
     xmlns:ui="http://example.org/ui-language/">
 <binding element="ui|listbox">
  <template allow-selectors-through="true">
   <div id="listbox-focus">
    <content includes="ui|listitem" apply-binding-sheets="true"/>
   </div>
  </template>
  <resources>
   <style>
    @namespace xbl url(http://www.w3.org/ns/xbl);
    @namespace uil url(http://example.org/ui-language/);
    uil|listbox { display: block; background: white; color: black; }
    uil|listbox > xbl|div#listbox-focus { border: ridge silver; }
    uil|listbox:focus > xbl|div#listbox-focus { border: inset silver; }
    uil|listitem { display: block; background: white; color: black; }
    uil|listitem[selected] { display: block; background: navy; color: white;}
   </style>
  </resources>
  ...
 </binding></xbl>

In the following example, the locked attribute is used to keep the children of the bound element in the location that the user has selected. By default, the listitem elements would be placed in the first content element, but because it is locked, they will instead go into the second one.

<xbl xmlns="http://www.w3.org/ns/xbl"
     xmlns:ui="http://example.org/ui-language/">
 <binding element="ui|duallist">
  <template>
   <div>
    <ui:listbox id="left" title="Selected Items">
     <content includes="ui|listitem" locked="true" id="leftList"/>
    </ui:listbox>
   </div>
   <div id="buttons">
    <ui:button id="move-right"> Move Right </ui:button>
    <ui:button id="move-left"> Move Left </ui:button>
   </div>
   <div>
    <ui:listbox id="right" title="Available Items">
     <content includes="ui|listitem" id="rightList"/>
    </ui:listbox>
   </div>
  </template>
  <implementation>
   ({
     xblBindingAttached: function() {
       this.shadowTree.getElementById('move-right').addEventListener(
         'click', this.moveRight, false
       );
       this.shadowTree.getElementById('move-left').addEventListener(
         'click', this.moveLeft, false
       );
     },
     moveRight: function(event) {
       this.shadowTree.getElementById('rightList').setInsertionPoint(
         this.shadowTree.getElementById('left').selectedElement
       );
     },
     moveLeft: function(event) {
       this.shadowTree.getElementById('leftList').setInsertionPoint(
         this.shadowTree.getElementById('right').selectedElement
       );
     },
   })
  </implementation>
 </binding>
</xbl>

2.6. The inherited Element

Expected context:
Any, but there must be a correct template element somewhere in the ancestor chain.
Expected children:
Anything.

The inherited element represents where the next inherited shadow tree is to be inserted. If the binding is the base binding (and thus has no inherited bindings) or if none of the bindings it inherits from have shadow trees, or if this is not the first inherited element in the binding's shadow tree, then the contents of the inherited element (if any) will be used instead. (See: the final flattened tree.)

Attributes

id
The id attribute.

While it is legal to nest inherited elements, it is pointless, since if one inherited element used its fallback content, any subsequent such elements will too.

The following binding wraps the bound element's children in a set of divs for extra styling. By using the inherited element, it has been designed such that it must be used in conjunction with other bindings: it will (if applied after the others) wrap the shadow trees of those templates. Contrast this with the example in the template section, which would not interact with other bindings. However, if this binding is not applied in conjunction with a binding that has a content element giving a place for the element's explicit children, then those children will not be in the final flattened tree.

<xbl xmlns="http://www.w3.org/ns/xbl">
 <binding id="wrapBy4">
  <template apply-author-sheets="true" allow-selectors-through="true">
   <div class="wrap1">
    <div class="wrap2">
     <div class="wrap3">
      <div class="wrap4">
       <inherited/>
      </div>
     </div>
    </div>
   </div>
  </template>
 </binding>
</xbl>

2.7. The xbl:attr Attribute

Expected element:
Any, but there must be a correct template element somewhere in the ancestor chain.

The xbl:attr attribute is a global attribute in the XBL namespace that specifies which attributes on the bound element should be forwarded to the element on which the attribute is found when the shadow content template is cloned. It is a space-separated list of QNames or QName pairs separated by equal signs, each possibly suffixed by a hash character ("#") and a type designation. (See: attribute forwarding.)

The value of the xbl:attr attribute must be a space-separated value of items that match the pattern given in the attribute forwarding section.

One of the major uses of the xbl:attr attribute is to implement one element in terms of another element which already has special behavior in user agents. This example shows how a ui:text element can be implemented in terms of an html:input element, with certain attributes being forwarded to that element directly.

<xbl:xbl xmlns:xbl="http://www.w3.org/ns/xbl"
         xmlns:ui="http://example.com/ui-language/"
         xmlns:html="http://www.w3.org/1999/xhtml">
 <xbl:binding element="ui|text">
  <xbl:template>
   <html:label>
    <html:span xbl:attr="xbl:text=label"/>
    <html:input xbl:attr="value=default disabled readonly" id="input"/>
   </html:label>
  </xbl:template>
  <xbl:implementation>
   ({
    get value () { return this.shadowTree.getElementById('input').value; },
    set value (val) { this.shadowTree.getElementById('input').value = val; },
   })
  </xbl:implementation>
 </xbl:binding>
</xbl:xbl>

2.8. The xbl:pseudo Attribute

Expected element:
Any, but there must be a correct template element somewhere in the ancestor chain.

The xbl:pseudo attribute is a global attribute in the XBL namespace that specifies the pseudo-element that, when used on the bound element, must be mapped to the element on which the attribute is found.

The value of the xbl:pseudo attribute must be a valid pseudo-element name, in lowercase, without the leading "::". The valid pseudo-elements are defined by the CSS specifications, and are "value", "choices", "label", "repeat-item", and "icon". Future versions of CSS might introduce new values. (See: matching pseudo-elements.)

The xbl:pseudo attribute is useful as a way to let author styles affect the insides of a shadow tree without exposing the exact construction of the tree. Here, the binding represents a composite widget with an icon, a label, a text field, and some buttons. Pseudo-elements are used for each part allowing the author to style each part separately.

<xbl:xbl xmlns:xbl="http://www.w3.org/ns/xbl"
         xmlns:html="http://www.w3.org/1999/xhtml">
 <xbl:binding id="input-dialog">
  <xbl:template>
   <xbl:div class="root">
    <xbl:div class="icon-block">
     <html:img xbl:pseudo="icon" xbl:attr="src=icon alt=alt"/>
    </xbl:div>
    <xbl:div xbl:pseudo="label" xbl:attr="xbl:text=label"/>
    <xbl:div class="field-block">
     <html:input xbl:pseudo="value" xbl:attr="value" id="field"/>
    </xbl:div>
    <xbl:div class="buttons-block">
     <html:button xbl:pseudo="choices" id="ok"> OK </html:button>
     <html:button xbl:pseudo="choices" id="cancel"> Cancel </html:button>
    </xbl:div>
   </xbl:div>
  </xbl:template>
  ...
 </xbl:binding>
</xbl:xbl>

An author-level stylesheet for a document using the binding might look like:

textDialog { binding: url(dialogs.xml#input-dialog); }
textDialog::value { background: white; color: black; }
textDialog::choices { border: outset; }

2.9. The div Element

Expected contexts:
template
content
inherited
div
Expected children:
Anything. Of particular interest, the content and inherited elements may occur as descendants, and non-XBL descendant elements may host xbl:attr and xbl:pseudo attributes.

The div element has no intrinsic meaning. It is intended to be used as a styling hook for presentational bindings.

Attributes

id
The id attribute.
class
A space-separated list of keywords relevant to the element that could be useful as stylistic hooks. This is a "class" attribute (which means, for example, that the CSS "." shorthand can be used to match div elements based on their class attribute). The class attribute doesn't apply to other XBL elements, only to div.
state
A free-form attribute with no predefined meaning that can be used as a stylistic hook, to store state, or for other purposes as desired by the binding author.
title
Text representing advisory information that the user agent should show to the user upon request (e.g., on a graphical browser, the contents of this attribute could be shown as a tooltip when the user indicates the element with a mouse pointer). The title attribute doesn't apply to other XBL elements, only to div.

The div element in XBL is not the same element type as the div element in HTML, but it is intended to be used in similar ways (and shares the name for that reason).

Many of the examples in this specification use the div element.

The following example uses the state attribute so that the CSS style sheet can render the shadow tree differently based on whether the switch that the binding represents is turned on or off.

<xbl xmlns="http://www.w3.org/ns/xbl">
 <binding id="switch">
  <template>
   <div class="wrapper">
    <div id="main" state="off"/>
   </div>
  </template>
  <handlers>
   <handler event="click">
    this.shadowTree.getElementById('main').setAttribute('state',
      this.shadowTree.getElementById('main').getAttribute('state') == 'on' ?
      'off' : 'on');
   </handler>
  </handlers>
  <resources>
   <style>
    #main[state=off] { ... }
    #main[state=on] { ... }
   </style>
  </resources>
 </binding>
</xbl>

2.10. The handlers Element

Expected context:
binding
Expected children:
handler: zero or more.

The handlers element's event handlers can be called for events that flow through the bound element. During capture, target, bubbling, and default phases, when a given event is received by a bound element, if a corresponding event listener has been attached to the handlers element, then the event will be forwarded to that event listener. (See: event forwarding, binding attachment and detachment.)

Typically, event handlers are defined using handler elements.

Attributes

id
The id attribute.

The following example shows how handlers can be used with any event listener mechanism.

<xbl xmlns="http://www.w3.org/ns/xbl">
 <binding id="test">
  <handlers id="test-handlers"/>
  ...
 </binding>
 <script>
  document.getElementById('test-handlers').addEventListener('click', function (event) {
    // this will get called for every click event that bubbles through 
    // any element that is bound to the "test" binding above.
    ...
  }, false);
 </script>
</xbl>

2.11. The handler Element

Expected context:
handlers
Expected children:
Depends on the scripting language.

The handler element describes a single event handler. This handler is attached to its parent handlers element, which is used as an event forwarding target when handling events on the bound element. (See: event handlers.) It wraps a script that is executed when the event handler is matched.

Attributes

id
The id attribute.
event
The event attribute describes the specific event that this handler is listening for. (See: registering event handlers with the handler element.)
phase
This attribute specifies the phase of the event flow that this handler should monitor. When specified, the value must be one of capture, target, bubble, or default-action. If capture is specified, then the event handler must only be fired during the capturing phase of event propagation. If target is specified, then the event handler must only be fired during the target phase. If default-action is specified, then the event handler must only be fired during the default phase (if it occurs). Otherwise, the handler must only be fired during the bubbling phase. (See: registering event handlers with the handler element.)
trusted
This attribute specifies whether the handler should be limited to trusted events. When specified, it must have the value true or the value false. If true is specified, then the event handler must only be fired if the event's trusted attribute is true. Otherwise, the value of the trusted flag does not affect the event handler. (See: registering event handlers with the handler element.)
propagate
The propagate attribute specifies whether after processing all listeners at the current node, the event is allowed to continue on its path (either in the capture or the bubble phase). When specified, it must have the value stop or the value continue. If the value is stop, then propagation will be stopped, otherwise it won't. It has no effect if the phase attribute has the value default-action. (See: registering event handlers with the handler element.)
default-action
The default-action attribute specifies whether after processing of all listeners for the event, the default action for the event (if any) should be performed or not. (See: registering event handlers with the handler element.)
button
The button attribute imposes a filter on the handler. It is used with mouse handlers to specify a particular button. (See: mouse event handler filters.)
click-count
The click-count attribute imposes a filter on the handler. It is used with mouse handlers to specify how many clicks must have occurred. (See: mouse event handler filters.)
modifiers
The modifiers attribute imposes a filter on key and mouse handlers. It is used with mouse and key handlers to specify particular modifier keys. (See: mouse event handler filters, key event handler filters, modifiers.)
key
The key attribute imposes a filter on key handlers. It is used with key handlers to specify which keys to listen for. (See: key event handler filters.)
key-location
The key-location attribute imposes a filter on key handlers. It is used with key handlers to specify which keys to listen for. (See: key event handler filters.)
text
The text attribute imposes a filter on text input handlers. It is used with text input handlers to specify which characters to listen for. (See: text input event handler filters.)
prev-value
The prev-value attribute imposes a filter on mutation handlers. It is used with mutation handlers to specify what prev-value to listen for. (See: mutation event handler filters.)
new-value
The new-value attribute imposes a filter on mutation handlers. It is used with mutation handlers to specify what new-value to listen for. (See: mutation event handler filters)
attr-name
The attr-name attribute imposes a filter on mutation handlers. It is used with attribute mutation handlers to specify which attribute to listen to for changes. (See: mutation event handler filters)
attr-change
The attr-change attribute imposes a filter on mutation handlers. It is used with attribute mutation handlers to specify the type of change to listen for. (See: mutation event handler filters.)

If a handler element is marked (via the script-type attribute of the xbl element) as being in a language that the UA does not support then the UA must ignore it, meaning it must not be used for the event handler definitions of any binding.

How UAs must handle nodes inside handler elements depends on the language used. (See: loading and running scripts, event handlers.)

handler blocks are evaluated each time they are fired. Changes to the handler elements therefore take effect the next time the event is fired.

The following binding implements a link which, when clicked once with the primary button and with no key modifiers, or, when focused and sent a keypress of the Enter key with no modifiers, will cause the link to be followed.

It will only do this if the click or the keypress is a real event triggered by the user; it won't do it for events faked by script. However, if the event faked by script is a DOMActivate event, then it will follow the link, because the handler for the DOMActivate event doesn't check that the event is trusted. (If it did, it would never fire, because the event is dispatched by the binding, and therefore is not trusted.)

<xbl xmlns="http://www.w3.org/ns/xbl">
 <binding id="events">
  <handlers>
   <handler event="click" phase="default-action"
            button="1" click-count="1" modifiers="none"
            trusted="true">
    this.activate();
   </handler>
   <handler event="keypress" phase="default-action"
            key="Enter" modifiers="none"
            trusted="true">
    this.activate();
   </handler>
   <handler event="DOMActivate" phase="default-action">
    if (event.target == this.boundElement)
      this.boundElement.ownerDocument.location.href = this.href;
   </handler>
  </handlers>
  ...
  <!-- it is assumed that the implementation for this binding
       implements a .activate() method that fires the DOMActivate
       event on itself. -->
 </binding>
</xbl>

2.12. The resources Element

Expected context:
binding
Expected children (in any order):
style: zero or more.
prefetch: zero or more.

The resources element contains a list of style sheets to apply when using this binding, as well as a list of files (images, videos, sound files, etc) to optionally preload.

Attributes

id
The id attribute.

2.13. The style Element

Expected context:
resources
Expected children:
If the element has no src attribute: depends on the styling language.
If the element does have a src attribute: none.

The style element is used to specify a style sheet that is to be applied to the bound element and to the shadow content generated by the binding, as well as to any explicit children (and their descendants) assigned to content elements in the shadow content whose apply-binding-sheets attribute is set.

The style element in XBL never applies styles to elements in the bound document other than the bound element (and possibly its children). It never affects any ancestors of the bound element, or any nodes in any other bindings or binding templates.

Attributes

id
The id attribute.
media
The media attribute specifies the intended destination medium for style information. If specified, the value of the attribute must be a valid Media Query (media_query token). How the value of this attribute is interpreted is defined by Media Queries. If this attribute is not specified, then there is no restriction on which media the style sheet should be applied to (same as specifying media="all"). [MQ]
src
The src attribute specifies the URI to a resource of the type given by the XBL subtree's style-type attribute. If the attribute is specified, the contents of the element must be ignored (even if the resource could not be fetched or was of the wrong type). (See: binding style sheets.)

If a style element is marked (via the style-type attribute of the xbl element) as being in a language that the UA does not support, the UA must ignore it. Similarly, if the style element points (using the src attribute) to a resource that is either unavailable, or not of the type specified by the style-type attribute of the xbl element (or implied by its absence), then it is in error and the UA must ignore it. In both cases, "ignoring it" means it must not be used to style anything.

How UAs must handle nodes inside style elements depends on the language used. (See: binding style sheets.)

For a summary of the various ways that content can be styled in the presence of XBL, see the styling summary section.

2.14. The prefetch Element

Expected context:
resources
Expected children:
None.

The prefetch element can be used to list resources that may be pre-loaded for performance reasons.

Support for this element is optional. UAs may ignore it.

Attributes

id
The id attribute.
src
A URI to a resource (such as an image) that the binding might use later.

The following binding uses two images; it sets the source of an HTML img element programmatically to refer to those images. To increase the chance that the "green.png" image is available straight away when it is used, it uses a prefetch element and specifies that that image will be needed.

<xbl xmlns="http://www.w3.org/ns/xbl"
     xmlns:html="http://www.w3.org/1999/xhtml">
 <binding id="light">
  <template>
   <html:img id="l" src="red.png" alt=""/>
  </template>
  <resources>
   <prefetch src="red.png"/> <!-- this one isn't necessary, since
    the UA will fetch this one as soon as it sees the <html:img> element -->
   <prefetch src="green.png"/>
  </resources>
  <implementation>
   ({
      red: function() {
        this.shadowTree.getElementById('l').src = 'red.png';
      },
      green: function() {
        this.shadowTree.getElementById('l').src = 'green.png';
      },
   })
  </implementation>
 </binding>
</xbl>

This binding might be used as follows:

<!DOCTYPE HTML>
<html>
 <head>
  <title>Light Demo</title>
  <style>
   #light { binding: url(demo.xml#light); }
  </style>
 </head>
 <body>
  <p id="light">Red</p>
  <p>
   <input type="button" onclick="doRed()" value="red">
   <input type="button" onclick="doGreen()" value="green">
  </p>
  <script>
   var light = document.getElementById('light');
   function doRed() {
     light.textContent = "Red";
     if (light.red)
       // binding might not be applied, so only call the method if it is