Developer Network Home - Help

Yahoo! UI Library: Button

Yahoo! UI Library: Button

The Button Control enables the creation of rich, graphical buttons that function like traditional HTML form buttons. Unlike traditional HTML form buttons, buttons created with the Button Control can have labels that are different from their value. With the inclusion of the optional Menu Control, the Button Control can also be used to create menu buttons and split buttons, controls that are not available natively in HTML. Moreover, the Button Control allows you to create more visually engaging implementations of radio-button and check-box controls.

Button Types

The Button Control enables the creation of eight different types of buttons:

Push Button (type "push")
Basic push button that can execute a user-specified command when pressed.
Link Button (type "link")
Navigates to a specified url when pressed.
Submit Button (type "submit")
Submits the parent form when pressed.
Reset (type "reset")
Resets the parent form when pressed.
Checkbox Button (type "checkbox")
Maintains a "checked" state that can be toggled on and off.
Radio Button (type "reset")
Maintains a "checked" state that can be toggled on and off. Use with the ButtonGroup class to create a set of controls that are mutually exclusive; checking one button in the set will uncheck all others in the group.
Menu Button (type "menu")
When pressed will show/hide a menu.
Split Button (type "split")
Can execute a user-specified command or display a menu when pressed.

Getting Started

To use the Button Control, include the following source files:

YUI dependency configurator.

YUI Dependency Configurator:

Instead of copying and pasting the filepaths above, try letting the YUI dependency Configurator determine the optimal file list for your desired components; the Configurator uses YUI Loader write out the full HTML for including the precise files you need for your implementation.

Note: If you wish to include this component via the YUI Loader, its module name is button. (Click here for the full list of module names for YUI Loader.)

Where these files come from: The files included using the text above will be served from Yahoo! servers; see "Serving YUI Files from Yahoo!" for important information about this service. JavaScript files are minified, meaning that comments and white space have been removed to make them more efficient to download. To use the full, commented versions or the -debug versions of YUI JavaScript files, please download the library distribution and host the files on your own server.

Order matters: As is the case generally with JavaScript and CSS, order matters; these files should be included in the order specified above. If you include files in the wrong order, errors may result.

Using "CSS skins": One of the files listed above contains a CSS "skin" for the Button Control. For this skin CSS to work correctly, you will need to apply the CSS class "yui-skin-sam" to an element that is a parent of the element in which the component lives. You can usually accomplish this simply by putting the class on the <body> tag:

<body class="yui-skin-sam">

For more information on skinning YUI components and making use of default skins, see our Understanding YUI Skins article here on the website.

Basic Setup

Buttons can be created with or without existing HTML. In either case, a Button's HTML is composed of two <span> elements wrapping a <button> element or (in the case of Buttons of type "link") an <a> element.

The Button Control is defined by YAHOO.widget.Button and can be instantiated three different ways:

Using an existing <input>, <button>, or <a> element

A Button can be created using an existing <input>, <button>, or <a> element as a source element:

Pass the id of the source element as the first argument to the Button's constructor. The attributes of the source element are captured and used for the creation of a new element that replaces the source element inline. Additional configuration attributes for a Button can be set at instantiation time by specifying them in an object literal that is passed as the second argument to the Button's constructor. Note: the value of configuration attributes passed to the Button constructor will trump those of the corresponding HTML attributes of the original source element.

Using no existing HTML

To build a Button without any existing HTML, pass a set of configuration attributes as a single argument to the constructor using an object literal.

In most cases, it is necessary to specify the button's id, type, label and container (the HTML element that the button should be appended to once created). If an id is not specified for the button, one will be generated using the generateId method of the Dom utility. Similarly, if the "type" attribute is omitted, the default type of "button" will be applied.

Using pre-defined Button Control HTML

A Button can be created using pre-defined Button Control HTML.

To instantiate a Button using the Button Control HTML, pass the id of the Button's <span> element as the first argument to constructor and any additional configuration attributes as the second argument via an object literal.

Using Button

This section describes several common uses and customizations of the Button Control:

Using Button with YAHOO.util.Event.onContentReady

As the Button Control can be used to enhance existing HTML <input>, <button>, or <a> elements, it is recommended that Button Controls be instantiated as soon as the elements they are replacing are available in the DOM. This helps minimize any flicker or redraw that might result from the replacement of the source HTML element with its corresponding Button instance HTML.

To instantiate a Button instance as soon as its source HTML element is available in the DOM, use the onContentReady method of the Event utility. For example, consider the following HTML:

To instantiate a Button Control as soon as this <input> element is available in the DOM, pass the source element's id (in this case "ok-button") as the first argument to the YAHOO.util.Event.onContentReady method along with a reference to the function to be called when the element is ready.

The onContentReady method is especially useful when creating a group of Buttons at once. In this case, wrap the source HTML elements in a containing element and give it a unique id. For example:

Pass the id of the parent element (in this case "buttons") to the YAHOO.util.Event.onContentReady method along with a reference to the function to be called when the element is ready

Usage of the onContentReady method is demonstrated in many of the Button Control examples. For more information, read the section titled Using the onAvailable and onContentReady Methods section of the Event utility's landing page.

Styling Types

Button uses CSS classes to provide an easy way to style all of the various types. All of the CSS classes used by Button are prefixed with "yui-" and the root element of every Button instance has two classes applied: a generic class of "yui-button" and a type-specific class (for example: "yui-split-button). This strategy allows for the application of generic styles to all buttons while at the same time facilitating type-specific styling. For example:

Styling State

Like styling types, Button state is styled through the use of CSS classes. There are four states common to all of the various types of buttons:

State Description
The default rendering of the focus state of a Button. Triggered when a Button receives focus.
The default rendering of the hover state of a Button. Triggered when the user hovers over a Button with the mouse.
The default rendering of the active state of a Button. Triggered when a Button is depressed - either by the user mousing down on a Button or by pressing the Enter key or spacebar when a Button has focus.
The default rendering of the disabled state of a Button. Triggered when the button is disabled.

For states that are common to all Buttons, two classes are applied: a generic class name (i.e. yui-button-[state]) and a type-specific state class name (yui-[type]-button-[state]). For example:

This strategy allows for the definition of generic styles that apply to all states of all Button instances, while providing a means for uniquely styling states for Buttons of a specific type.

In addition to the common states, there are some states that are specific only to certain Button types. Buttons of type "checkbox" and "radio" both have a "checked" state represented by both a generic and type-specific CSS class:

The default rendering for the "checked" state is illustrated below:

The default rendering of the checked state of a Button of type checkbox.

Buttons of type "split" have a unique "activeoption" state that represents that the user has invoked the display of the Button's optional menu. As this state is unique to the "split" type, only one CSS class of "yui-split-button-activeoption" is applied to the Button's root element. The "option" event is fired either in response to the use of a keyboard shortcut (by default Ctrl + Shift + M) or by mousing down on a specific region of the Button. The default style for the "activeoption" state is illustrated below:

The default rendering of the activeoption state of a Button of type split.

Styling Focus

When Button instances recieve focus, their inner <button> or <a> element is outlined or highlighted in some way by the browser. Typically the rendering of the focus outline follows that of native OS controls for the platform, however, the style can vary depending on the OS + browser combination. For example, in Firefox the focus outline is drawn as a dotted border, while in Safari the focus outline is drawn as a blue border. Even though the focus style is inconsistent across OS + browser combinations, this inconsistency is of benefit to the user for two reasons: it provides a visual indication of keyboard navigability and does so in a way that is familiar on their OS + browser of choice.

If it is absolutely necessary to hide the focus outline for Button instances it is possible to do in all of the supported browsers with the exception of Opera. To disable the focus outline in Internet Explorer, set the hideFocus attribute to "true." For example:

Or if you are creating Buttons from script:

In Firefox and Safari, set the outline CSS property to "none." For example:

Using Button with HTML forms

Buttons created with the Button Control can be used with or without HTML forms. When appended to a form, each Button Control will behave like a traditional HTML form element. Resetting a form containing Button Controls will result in each Button reverting to its initial value and/or state. Each Button Control also listens for the "submit" event of its parent form and will create a hidden field representing its name and value in response to the firing of that event to ensure the form's data set is accurate when the form is submitted.

Using ButtonGroup

The ButtonGroup class creates a set of buttons that are mutually exclusive; checking one button in the group will uncheck all others in the group. The ButtonGroup class is defined by YAHOO.widget.ButtonGroup and a ButtonGroup's root HTML element is a <div>.

Creating a ButtonGroup using existing HTML

A ButtonGroup can be created from a set of existing <input type="radio"/> elements:

To instantiate a ButtonGroup from existing HTML, pass the id of the ButtonGroup's <div/> element as the first argument to the ButtonGroup constructor and any additional configuration attributes as the second argument via an object literal. The ButtonGroup will automatically search its child nodes for HTML radio buttons (<input type="radio"/>) and use those elements to create instances of YAHOO.widget.Button of type "radio."

Alternatively, each Button in a ButtonGroup can be defined using the YUI Button HTML: An element with a class of "yui-button" and "yui-radio-button" containing a element with a class of "first-child" containing a <button/> element.

To instantiate a ButtonGroup using the Button Control HTML, pass the id of the ButtonGroup's root element (the element with the classes "yui-buttongroup" and "yui-radio-button" applied) as the first argument to constructor and any additional configuration attributes as the second argument via an object literal.

Creating a ButtonGroup without existing HTML

To build a ButtonGroup with no existing HTML, pass a set of configuration attributes as a single argument to the constructor using an object literal. Add buttons to the ButtonGroup via the addButton or addButtons methods.

The name of the ButtonGroup will automatically be applied to each Button and each Button's type will be set to "radio."

Using Button with Menu

By including the Menu family of controls, it is possible to create two different types of buttons that incorporate a menu:

Menu Button (type "menu")
When pressed will show/hide a menu.
Split Button (type "split")
Can execute a user-specified command or display a menu when pressed.

Like all other Buttons, menu buttons and split buttons can be created with or without existing HTML. In either case, create a menu button or a split button by setting the Button's "type" attribute to "menu" or "split" and "menu" attribute to one of the following values:

  • Object specifying a YAHOO.widget.Menu instance.
  • Object specifying a YAHOO.widget.Overlay instance.
  • String specifying the id attribute of the <div> element used to create the menu. By default the menu will be created as an instance of YAHOO.widget.Overlay. If the default CSS class name for YAHOO.widget.Menu is applied to the <div> element, it will be created as an instance of YAHOO.widget.Menu.
  • String specifying the id attribute of the <select> element used to create the menu.
  • Object specifying the <div> element used to create the menu.
  • Object specifying the <select> element used to create the menu.
  • Array of object literals, each representing a set of YAHOO.widget.MenuItem configuration attributes.
  • Array of strings representing the text labels for each menu item in the menu.

Since the "menu" attribute can be set to the id of an existing <select> element, the "menu" and "split" types can be used to collapse two HTML form controls (<input> and <select>) into one DHTML control. For example, start with an <input> and <select> element:

Next, pass the id of the <input> as the first argument to the Button's constructor and the id of the code><select> element as the value of the "menu" configuration attribute:

If the source <input> element's type was "submit," the button will automatically submit its parent form when the user clicks or presses the button or chooses an option from the button's menu.

Handling Events

All of the the events for Button and ButtonGroup (including DOM-based events such as "mouseover" or "click") can be listened for via addListener method (or on for short).

Note: To listen for DOM-based events, always use the provided event interface rather than attaching handlers directly to Button or ButtonGroup DOM elements.

The event object is passed to the handler function as the first argument. For DOM events, this is the actual event object.

For Button-specific events (i.e., non-DOM events), the first argument passed to the event handler is an object containing relevant event information. For change events, this includes prevValue (the previous value of the attribute) and newValue (the new value of the attribute).

Additionally, configuration attribute changes done via the set interface (e.g., oButton.set("checked", true);) can be cancelled by returning false from the beforeChange event.

Event listeners can be removed using removeListener.

Configuration Attributes

Configuration attributes are accessible at runtime through the Button and ButtonGroup get and set methods. For example:

See the reference table below as well as the API documentation for Button and ButtonGroup for a complete list of configuration attributes.

Skinning the Button Control

The Button Control comes with a default presentation or "skin," part of the "Sam Skin" visual treatment that accompanies most YUI controls. (Read more about the general approach to skinning YUI components in this in-depth article.) The default rendering of the various types of Buttons with the default "Sam Skin" applied is illustrated below:

Various buttons created with the Button Control using the Sam skin.

In the case of the Button Control, there is no "core" CSS treatment — which is to say that there is no CSS that is considered essential to the functioning of the control. All of the CSS provided with Button Control is part of the Sam skin visual treatment.

To explore the CSS which controls the Button Control's presentation, please review the CSS class reference below.

Reference Tables

The following tables contain information about configuration properties and CSS classes for Button and ButtonGroup:

Button Configuration Attributes

Name Type Default Description
See the API documentation for the complete list of properties and methods.
type String "button" String specifying the button's type. Possible values are: "push," "link," "submit," "reset," "checkbox," "radio," "menu," and "split."
label String null String specifying the button's text label or innerHTML.
value Object null Object specifying the value for the button.
name String null String specifying the name for the button.
tabindex Number null Number specifying the tabindex for the button.
title String null String specifying the title for the button.
disabled Boolean false Boolean indicating if the button should be disabled. (Disabled buttons are dimmed and will not respond to user input or fire events. Does not apply to button's of type "link.")
href String null String specifying the href for the button. Applies only to buttons of type "link."
target String null String specifying the target for the button. Applies only to buttons of type "link."
checked Boolean false Boolean indicating if the button is checked. Applies only to buttons of type "radio" and "checkbox."
container HTMLElement|String null HTML element reference or string specifying the id attribute of the element that the button's HTML should be rendered into.
srcelement HTMLElement|String false Object reference to the HTML element (either <input>, <button>, <a>, or <span>) used to create the button.
menu YAHOO.widget.Menu|
YAHOO.widget.Overlay|
HTMLElement|
String
|Array
null Object specifying the menu for the button. The value can be one of the following:
  • Object specifying a YAHOO.widget.Menu instance.
  • Object specifying a YAHOO.widget.Overlay instance.
  • String specifying the id attribute of the <div> element used to create the menu. By default the menu will be created as an instance of YAHOO.widget.Overlay. If the default CSS class name for YAHOO.widget.Menu is applied to the <div> element, it will be created as an instance of YAHOO.widget.Menu.
  • String specifying the id attribute of the <select> element used to create the menu.
  • Object specifying the <div> element used to create the menu.
  • Object specifying the <select> element used to create the menu.
  • Array of object literals, each representing a set of YAHOO.widget.MenuItemconfiguration attributes.
  • Array of strings representing the text labels for each menu item in the menu.
lazyloadmenu Boolean true Boolean indicating the value to set for the "lazyload" configuration property of the button's menu. Setting "lazyloadmenu" to true will defer rendering of the button's menu until the first time it is made visible. If "lazyloadmenu" is set to false, the button's menu will be rendered immediately if the button is in the document, or in response to the button's "appendTo" event if the button is not yet in the document. In either case, the menu is rendered into the button's parent HTML element. This attribute does not apply if a YAHOO.widget.Menu or YAHOO.widget.Overlay instance is passed as the value of the button's "menu" configuration attribute. YAHOO.widget.Menu or YAHOO.widget.Overlay instances should be rendered before being set as the value for the "menu" configuration attribute.
menuclassname String "yui-button-menu" String representing the CSS class name to be applied to the root element of the button's menu.
selectedMenuItem Number null Number representing the index of the item in the button's menu that is currently selected.
onclick Object null Object literal representing the code to be executed when the button is clicked. Format:
{
fn: Function, // The handler to call when the event fires.
obj: Object, // An object to pass back to the handler.
scope: Object // The object to use for the scope of the handler.
}
focusmenu Boolean true Boolean indicating whether or not the button's menu should be focused when it is made visible.

ButtonGroup Configuration Attributes

Name Type Default Description
See the API documentation for the complete list of properties and methods.
name String null String specifying the name for the button group. This name will be applied to each button in the button group.
disabled Boolean false Boolean indicating if the button group should be disabled. Disabling the button group will disable each button in the button group. Disabled buttons are dimmed and will not respond to user input or fire events.
value Object null Object specifying the value for the button group.
container null HTMLElement|String HTML element reference or string specifying the id attribute of the element that the button group's HTML should be rendered into.
checkedButton YAHOO.widget.Button null Reference to the button in the button group that is checked.

CSS Classes

The Button Control makes use of several CSS classes. You can either use the provided style sheet, or create a new one. The following is a reference of all of the classes used by the Button Control:

Name Description
yui-button Applied to a button's root <span> element.
yui-[button type]-button Applied to a button's root <span> element after the default class name of "yui-button," enabling the application of different default styles for each type of button.
first-child Applied to the <span> element that is the first child element of a button's root <span> element.
yui-button-focus Applied to a button's root <span> element when the button has focus.
yui-[button type]-button-focus Applied to a button's root <span> element to enable type-specific styling to be applied when a button has focus.
yui-button-hover Applied to a button's root <span> element when the user is hovering over the element with a pointing device.
yui-[button type]-button-hover Applied to a button's root <span> element to enable type-specific styling to be applied when the user is hovering over the element with a pointing device.
yui-button-active Applied to a button's root <span> element when the user has pressed the button but not released it.
yui-[button type]-button-active Applied to a button's root <span> element to enable type-specific styling to be applied when the user has pressed the button but not released it.
yui-split-button-activeoption Applied to a split button's root <span> element when the user has pressed the arrow portion of the button.
yui-button-checked Applied to the root <span> element for buttons of type "radio" and "checkbox" when the button is checked.
yui-[button type]-button-checked Applied to the root <span> element for buttons of type "radio" and "checkbox" to enable type-specific styling to be applied when the button is checked.
yui-button-disabled Applied to a button's root <span> element when the button is disabled.
yui-[button type]-button-disabled Applied to a button's root <span> element to enable type-specific styling to be applied when the button is disabled.
yui-buttongroup Applied to a button group's root <div> element.
yui-button-menu Applied to the root <div> element of the button's menu.
yui-[button type]-button-menu Applied to the root <div> element of the button's menu to enable type-specific styling for the button's menu.

Known Issues

  • Buttons flicker when setting the "label" attribute in Firefox 2

    Button makes use of the Gecko-specific CSS property "-moz-inline-box" in order to draw rounded corners for the default Sam skin. Use of this Gecko-specific property is used to supplement Gecko's lack of support for "inline-block" in Firefox 2, but it has one drawback: When a Button's "label" is changed, the Button fails to redraw at the correct width. This problem was filed as a bug and the fix was to use a timer to quickly add and then remove the Button's CSS class name. Doing so triggers the Button to redraw itself at the correct width. Unfortunately, this also results in a quick flicker as the Button is being redrawn, however, the flicker is currently considered more acceptable than the Button not redrawing at the correct width.

  • Menu instances appear at the incorrect position when placed inside a statically positioned scrolled element.

    There is bug in Menu where Menu instances will appear at the incorrect x and/or y position if any of its parent elements are both statically positioned and scrolled. This bug only manifests in Firefox 2, Safari, and Opera. The position of the Menu instance will be off by an amount equal to the value of the parent element's scrollTop and scrollLeft properties. To fix this issue, add listeners for the change events of the Menu instance's "x" and "y" configuration properties that adjust the Menu's position according to the value of its parent element's scrollTop and scrollLeft properties as illustrated in this example: http://yuiblog.com/sandbox/yui/v252/examples/button/example07.html.

  • Button name and value pairs missing from form data when the form is submitted via its submit method.

    As noted in the section above titled Using Button with HTML forms, each Button Control listens for the "submit" event of its parent form and will create a hidden field representing its name and value in response to the firing of that event to ensure the form's data set is accurate when the form is submitted. When submitting a form via JavaScript using the form's submit method, it is necessary to call YAHOO.widget.Button.addHiddenFieldsToForm (passing in a reference to the form to be submitted) beforehand. This is due to the fact that calling a form's submit method does not fire the form's "submit" event and a Button instance has no way to automatically append the necessary hidden field representing its name and value.

  • Button name and value pairs missing from form data when using the setForm of Connection Manager.

    As noted in the section above titled Using Button with HTML forms, each Button Control listens for the "submit" event of its parent form and will create a hidden field representing its name and value in response to the firing of that event to ensure the form's data set is accurate when the form is submitted. Therefore, since the hidden fields representing a Button instance's name and value pairs are only automatically append in response to the firing of the "submit" event, it is necessary to call YAHOO.widget.Button.addHiddenFieldsToForm (passing in a reference to the form to be submitted) before calling the setForm method of Connection Manager.

YUI on Mobile: Using Button Control with "A-Grade" Mobile Browsers

About this Section: YUI generally works well with mobile browsers that are based on A-Grade browser foundations. For example, Nokia's N-series phones, including the N95, use a browser based on Webkit — the same foundation shared by Apple's Safari browser, which is found on the iPhone. The fundamental challenges in developing for this emerging class of full, A-Grade-derived browsers on handheld devices are:

  • Screen size: You have a much smaller canvas;
  • Input devices: Mobile devices generally do not have mouse input, and therefore are missing some or all mouse events (like mouseover);
  • Processor power: Mobile devices have slower processors that can more easily be saturated by JavaScript and DOM interactions — and processor usage affects things like battery life in ways that don't have analogues in desktop browsers;
  • Latency: Most mobile devices have a much higher latency on the network than do terrestrially networked PCs; this can make pages with many script, css or other types of external files load much more slowly.

There are other considerations, many of them device/browser specific (for example, current versions of the iPhone's Safari browser do not support Flash). The goal of these sections on YUI User's Guides is to provide you some preliminary insights about how specific components perform on this emerging class of mobile devices. Although we have not done exhaustive testing, and although these browsers are revving quickly and present a moving target, our goal is to provide some early, provisional advice to help you get started as you contemplate how your YUI-based application will render in the mobile world.

More Information:

The YUI Button Control performs well on the Nokia N95 and generally not so well on the iPhone. The following is a preliminary list of observations and known issues with Button and the iPhone:

iPhone

  • YUI Button instances don't render correctly because the default style of <button> elements provided by Safari cannot be overridden with CSS.
  • YUI Button instances of type link do render correctly in Safari.
  • The iPhone platform currently lacks support for some of the DOM events (i.e. mouseover and mouseout) necessary to provide a hover style for Button instances.

Support & Community

The YUI Library and related topics are discussed on the on the ydn-javascript mailing list.

In addition, please visit the YUIBlog for updates and articles about the YUI Library written by the library's developers.

Filing Bugs & Feature Requests

The YUI Library's public bug tracking and feature request repositories are located on the YUI SourceForge project site. Before filing new feature requests or bug reports, please review our reporting guidelines.

Copyright © 2008 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings