Вы находитесь на странице: 1из 41

Welcome to the Yahoo!

User Interface Library (YUI)


A free, open-source JavaScript and CSS YUI Destinations:
library. The same one we use at Yahoo!
every day. In February, 2006, Yahoo! YUI Website
opened its frontend library under a http://developer.yahoo.com/yui
BSD license, making it freely avail-
Download YUI
able to all developers. Now the li- Read official documentation
brary that powers the world!s most vis- Explore searchable APIs
ited website can also power yours. Find user!s guides for every component

YUI provides a suite of JavaScript utilities and UI YDN-JavaScript


controls that help developers create rich, dy- http://tech.groups.yahoo.com/group/
namic interfaces within the browser. It also pro- ydn-javascript/
vides four core CSS utilities that help to normal-
ize your baseline styles and to build robust, se- Ask questions
mantic, CSS-driven page layouts utilizing a com- Discuss YUI development and usage
pact and flexible toolkit. Share your implementation with other de-
velopers
YUI is an á la carte library, one that allows you to
pick and choose which features you want on any
given page. The code is compact and efficient. SourceForge
If you enable server-side compression, no single http://sourceforge.net/projects/yui/
YUI component (other than the Rich Text Editor)
requires a download of more than 35KB — and Make feature requests
most are much smaller than that. Explore YUI: File bug reports
YUI ships with nearly 200 examples.
Today!s YUI consists of a CSS foundation, a core YUIBlog
of three essential utilities (YAHOO, Dom, and Download the library and explore the YUI
core — YAHOO Global Object, the Dom http://yuiblog.com
Event), numerous other utilities that empower
rich interactions (like Connection Manager, Drag Collection, and the Event Utility — and Read articles and watch videos about YUI,
& Drop, and Animation), and more than a dozen
their examples. Then start exploring JavaScript, CSS and more
rich UI controls ranging from DHTML windowing
to AutoComplete to a full Rich Text Editor. some of the other utilities like Animation, See YUI implementations in the wild
Connection Manager (for Ajax), and Drag Let others know about your own YUI im-
YUI provides support for what we consider to be & Drop. plementations
the “A-Grade” browsers: Firefox, Opera, Safari
and Internet Explorer. You can count on all of Next:
our components working across the A-Grade;
Then take a look at the UI controls like
rare exceptions are documented as “known is- AutoComplete and TabView and see how Weʼre working hard to improve YUI and better
sues” and you can rely on Yahoo! to work with you can transform your web page with just serve the YUI community. Please join YDN-
browser manufacturers to resolve known issues a few lines of code and a few KB of library JavaScript, follow the blog, and let the com-
as promptly as possible. munity know what youʼre doing with YUI.
includes.
YUI Library: Animation 2009-2-6 v2.7
Simple Use Case Interesting Moments in Animation YAHOO.util.Anim:
Event Fires... Arguments Properties
myAnimObj = new YAHOO.util.Anim("myDiv", {width:
{to: 100}, height: {to: 100}}); onStart ...when anim begins attributes (obj)
myAnimObj.animate(); onTween ...on every frame currentFrame (int)
[0] {frames: total frames, fps: duration (num)
Makes the HTML element whose id attribute is "myDiv" resize to a onComplete ...when anim ends
frames per second, duration: of totalFrames (int)
height and width of 100 pixels. animation in miliseconds} useSeconds (b)
These are Custom Event members of YAHOO.util.Anim; use these by subscribing:
Constructor (YAHOO.util.Anim, ColorAnim, etc.) myAnimInstance.onComplete.subscribe(myOnCompleteHandler);
YAHOO.util.Anim:
YAHOO.util.Anim(str | element target, obj Using the Motion Subclass Methods
attributes[, num duration, obj easing]);
Use the Motion subclass to define animations to/from a specific point, animate()
Arguments: using (optional) bezier control points. getEl()
(1) Element id or reference: HTML ID or element reference for the getStartTime()
element being animated. var attributes = {
isAnimated()
points: {
(2) Attributes object: Defines the qualities being animated; see stop(bFinish) if true, advances
to: [250, 450], to last frame of animation
below. control: [[100, 800], [-100, 200], [500, 500]]}};
(3) Duration: Approximate, in seconds. var anim = new YAHOO.util.Motion(element,
(4) Easing: Reference to an easing effect, member of attributes, 1, YAHOO.util.Easing.easeIn); Easing Effects
YAHOO.util.Easing. Members of YAHOO.util.Easing

Using the ColorAnim Subclass backBoth


Attributes Object backIn
Use the ColorAnim subclass to background, text or border colors.
backOut
animAttributes = {
animatedProperty: { var myAnim = new YAHOO.util.ColorAnim(element, {back bounceBoth
by: 100, //start at current, change by this much groundColor: { to: '#dcdcdc' } }); bounceIn
to: 100, //start at current, go to this myAnim.animate(); bounceOut
from: 100, //ignore current; start from this easeBoth
unit: 'em' //can be any legal numeric unit Using the Scroll Subclass easeBothStrong
} easeIn
Use the Scroll subclass to animate horizontal or vertical scrolling of an easeInStrong
}
overflowing page element. easeNone default; no easing
Note: Do not include to and by for the same animation property. easeOut
var attributes = {
scroll: { to: [220, 0] } easeOutStrong
Animation Properties }; elasticBoth
Use Animation to apply gradual transitions to these properties*: var anim = new YAHOO.util.Scroll(element, elasticIn
attributes, 1, YAHOO.util.Easing.easeOut); elasticOut
borderWidth height
bottom margin Solutions
fontSize opacity
left lineHeight Subscribe to an API method:
right padding
myAnimObj = new YAHOO.util.Anim(element, {width:
top width {to: 100}, height: {to: 100}});
*or to any other member of an element's style object that takes a numeric value myHandler = function(type, args) {
someDiv.innerHTML = args[0].fps; //gets frames-
Dependencies per-second from the onComplete event}
myAnimObj.onComplete.subscribe(myHandler);
Animation requires the YAHOO Global Object, Dom Collection, and myAnimObj.animate();
Event Utility.
YUI Library: AutoComplete 2009-2-6 v2.7
Simple Use Case Interesting Moments YAHOO.widget.
Event Arguments (passed via args array)
AutoComplete Key
Markup: Properties:
<div id=”myAutoComplete”> textboxFocusEvent/
<input id="myInput" type="text"> textboxBlurEvent/ [0] AC instance alwaysShow Container
<div id="myContainer"></div> textboxChangeEvent (b)
</div> textboxKeyEvent [0] AC instance; [1] keycode int
animHoriz (b)
[0] AC instance; [1] query string; [2] request
Script: dataRequestEvent
object animSpeed (int)
var myAutoComp = new YAHOO.widget.AutoComplete ("myInput", animVert (b)
"myContainer", myDataSource); [0] AC instance; [1] query string; [2] results
dataReturnEvent applyLocalFilter (b)
array
Instantiates a new AutoComplete object, myAutoComp, which queries an dataErrorEvent 0] AC instance; [1] query string autoHighlight (b)
existing DataSource myDataSource. containerExpandEvent/ delimChar (char || array)
containerCollapseEvent/ [0] AC instance forceSelection (b)
Constructor containerPopulateEvent highlightClassName
itemArrowToEvent/ (string)
[0] AC instance; [1] <li> element
YAHOO.widget.AutoComplete(str | el ref input field, str | itemArrowFromEvent maxResultsDisplayed
el ref suggestion container, obj DataSource instance[, itemMouseOverEvent/ (int)
[0] AC instance; [1] <li> element
obj configuration object]); itemMouseOutEvent
minQueryLength (int)
Arguments: [0] AC instance; [1] <li> element; [2] item
itemSelectEvent prehighlightClass Name
(1) HTML element (string or object): Text input or textarea element. data object or array
selectionEnforceEvent [0] AC instance (string)
(2) HTML element (string or object): Suggestion container.
[0] AC instance; [1] query string; [2] prefill queryDelay (int)
(3) DataSource instance (obj): An instantiated DataSource object; see below typeAheadEvent
for DataSource types and constructor syntax. string queryMatchCase (b)
(4) Configuration object (object): An optional object literal defines property unmatchedItemSelectEvent [0] AC instance; [1] user selected string queryMatchContains (b)
values of an AutoComplete instance. Subscribe to AutoComplete Custom Events on your AutoComplete instance: queryMatchSubset (b)
myAC.containerExpandEvent.subscribe(myFn[, myObj, bScope]); queryQuestionMark (b)
Solutions resultsTypeList (b)
Abstract Methods suppressInputUpdate (b)
Custom cell formatting: Method Description typeAhead (b)
myAC.resultsTypeList = false; // pass data as an object This overridable abstract method gives typeAheadDelay (int)
myAC.formatResult = function(oData, sQuery, sMatch) { implementers access to the DataSource useIFrame (b)
return (sMatch + "(" + oData.param + ")" ); doBeforeLoadData response before it is consumed by the useShadow (b)
} AutoComplete instance and rendered into
the results container.
Custom local filtering:
This overridable abstract method gives
myAC.applyLocalFilter = true; // pass results thru filter implementers access to result data and
myAC.filterResults = function(sQuery, oFullResponse, DOM elements after the container has been
oParsedResponse, oCallback) { doBeforeExpandContainer rendered with results but before it is
var matches = [], matchee; displayed to the user, for example to move
for(var i=0; i<oParsedResponse.results.length; i++) { the container to a different position on the
if(oParsedResponse.results[i].someValue > 0) { screen.
matches[matches.length] =
oParsedResponse.results[i]
} Dependencies
} AutoComplete requires the YAHOO Global Object, Dom, and Event, and
oParsedResponse.results = matches;
DataSource. Animation (for animated opening of the suggestion container) is
return oParsedResponse;
optional.
}
YUI Library: Browser History Manager 2009-2-6 v2.7
Getting Started with Browser History Manager Storing New History Entries: The navigate Method YAHOO.util.History Methods:
getBookmarkedState(str module)
1. Required Markup Any registered module can create a new history entry at any time. Doing so returns str bookmarked state
creates a new “stop” to which the user can navigate to via the back/forward getCurrentState(str module) returns str
The Browser History Manager requires the following in-page markup: buttons and that can be bookmarked in the browser. You can create new history current state
entries in your script using the navigate method. getQueryStringParameter(str param
<iframe id="yui-history-iframe" src="asset"></iframe>
name[, str query string]) returns str
<input id="yui-history-field" type="hidden"> YAHOO.util.History.navigate(str module, str new state); param value
initialize(str stateFieldId, str
1. The asset loaded in the IFrame must be in the same domain as the Arguments: histFrameId)
page (use a relative path for the src attribute to make sure of that) navigate(str module, str state) returns
2. The asset loaded in the IFrame does not have to be an HTML 1. module: Module identifier you used when you registered the module. Boolean success
document. It can be an image for example (if you use an image that 2. new state: String representing the new state of the module. multiNavigate(arr states) returns
Boolean success
you also happen to use in your page, you will avoid an unnecessary Note: The navigate method returns a Boolean indicating whether the new state was successfully stored.
Note: The multiNavigate method allows you to change the state of several modules at once, creating a single register(str module, str initial state, fn
round-trip, which is always good for performance) callback[, obj associated object, b
history entry, whereas several calls to navigate would create several history entries.
3. This markup should appear right after the opening <body tag. scope])

2. Module Registration and the register Method A Sample Interaction


Dependencies
Use the following code to register a module:
YAHOO.util.History.register(str module, str initial Browser History Manager
state, fn callback[, obj associated object, b scope]) requires the YAHOO Global
Object and the Event Utility.
Arguments:
1. module: Arbitrary, non empty string identifying the module.
2. Initial state: Initial state of the module (corresponding to its earliest
history entry). YAHOO.util.History.getBookmarkedState may
be used to find out what this initial state is if the application was
accessed via a bookmark.
3. callback: Function that will be called whenever the Browser History
Manager detects that the state of the specified module has changed.
Use this function to update the module’s UI accordingly.
4. associated object: Object to which your callback will have access;
often the callback’s parent object.
5. scope: Boolean – if true, the callback runs in the scope of the
associated object.
3. Using the onReady Method
Once you’ve registered at least one module, you should use the Browser
History Manager's onReady method. In your handler, you should
initialize your module(s) based on their current state. Use the function
YAHOO.util.History.getCurrentState to retrieve the current
state of your module(s).
YAHOO.util.History.onReady(function () {
var currentState =
YAHOO.util.History.getCurrentState("module");
// Update UI of module to match current state
});
4. Initializing the Browser History Manager
Before using the Browser History Manager, you must initialize it, passing
in the id of the required HTML elements created in step 1:
YAHOO.util.History.initialize("yui-history-field",
"yui-history-iframe");
YUI Library: Button 2009-2-6 v2.7
Simple Use Cases: YAHOO.widget.Button Key Interesting Moments in Button YAHOO.widget.Button:
See online docs for a complete list of Button's Events. Properties
Create a Button instance using existing markup:
focus blur CSS_CLASS_NAME
Markup: click option NODE_NAME
<input type=”button” id=”mybutton” name=”mybutton” All Button events are Custom Events (see Event Utility docs); subscribe to these events using “addListener”:
value=”Press Me!”> (e.g. oButton.addListener(“click”, fn); ). YAHOO.widget.Button:
Script: Methods
var oButton = new YAHOO.widget.Button("mybutton"); Key Interesting Moments in ButtonGroup
See online docs for a complete list of ButtonGroup's Events. blur()
Create a Button instance using script alone: Event: Event Fields: destroy()
var oButton = checkedButtonChange type (s), prevValue (s), newValue (s) focus()
new YAHOO.widget.Button({ label:"Press Me!”}); All ButtonGroup events are Custom Events (see Event Utility docs); subscribe to these events using getForm()
addListener (e.g. oButtonGroup.addListener(“checkedButtonChange”, fn); ). getMenu()
hasFocus()
Constructor: YAHOO.widget.Button Key Button Configuration Options isActive()
See online docs for complete list of Buttion configuration options. set([attr name], [attr value])
YAHOO.widget.Button(str|HTMLElement|obj element[, obj get([attr name])
configuration object]); Option (type) Default Description
type (s) “push” String specifying the button's type. (Possible
Arguments: values are: "push," "link," "submit," "reset," YAHOO.widget. ButtonGroup:
(1) element: HTML ID or HTMLElement of existing markup to "checkbox," "radio," "menu," and "split.") Properties
use when building Button. If neither, this is treated as the label (s) null The button's text label or innerHTML.
CSS_CLASS_NAME
Configuration object. name (s) null The name for the button. NODE_NAME
(2) configuration object: JS object defining configuration value (o) null The value for the button.
properties for the Button instance. See Configuration section checked (b) false Boolean indicating if the button is checked.
(For buttons of type "radio" and "checkbox.")
YAHOO.widget. ButtonGroup:
for full list. Methods
disabled (b) false Boolean indicating if the button should be
disabled. (Disabled buttons are dimmed and addButton(button)
Simple Use Cases: YAHOO.widget.ButtonGroup will not respond to user input or fire events.) addButtons([]buttons)
href (s) null The href for the button. (For to buttons of type check(index)
Create a ButtonGroup instance using existing markup: "link.") destroy()
Markup: menu (o) null Element id, array of YAHOO.widget.MenuItem focus(index)
<div id="mybuttongroup"> configuration attributes, or getButton(index)
<input type="radio" name="myfield" value="One"> YAHOO.widget.Menu instance. (For buttons of getButtons()
<input type="radio" name="myfield" value="Two"> type "menu" and “split.”) getCount()
<input type="radio" name="myfield" value="Three"> menumaxheight (n) 0 The max height height of a Menu before it removeButton(index)
</div> scrolls. set([attr name], [attr value])
Script: menualignment (a) [“tl”,”bl”] How the Menu is aligned to the Button. get([attr name])
var oButtonGroup = new Button options can be set in the constructor's second argument (eg, {disabled: true}) or at runtime via
set (eg, oButton.set("disabled", true);).
YAHOO.widget.ButtonGroup("mybuttongroup");
Dependencies
Key ButtonGroup Configuration Options
Constructor: YAHOO.widget.ButtonGroup See online docs for complete list of ButtonGroup configuration options. Button requires the
YAHOO.widget.ButtonGroup(str|HTMLElement|obj element[, Option (type) Default Description YAHOO Object,
obj configuration object]); name (s) null The name for the button group (will be applied Event, Dom, and
to each button in the button group). Element. Optional:
Arguments: disabled (b) false Boolean indicating if the button group should be Container Core and
(1) element: HTML ID or HTMLElement of existing markup to disabled. (Disabling the button group will Menu.
use when building ButtonGroup. If neither, this is treated as disable each button in the button group.)
the Configuration object. value (o) null Object specifying the value for the button.
(2) configuration object: JS object defining configuration checkedButton (o) null The checked button in the button group.
properties for the ButtonGroup instance. See Configuration ButtonGroup options can be set in the constructor's second argument (eg, {disabled: true}) or at runtime
via set (eg, oButtonGroup.set("disabled", true);).
section for full list.
YUI Library: Calendar and CalendarGroup 2009-2-6 2.7
Simple Use Case: YAHOO.widget.Calendar Interesting Moments in Calendar, CalendarGroup YAHOO.widget.Calendar &
See online docs for complete list of Calendar and CalendarGroup events. CalendarGroup Properties
Markup:
<div id="container"></div> Event Fires... Arguments: id (str)
selectEvent After a date is selected. Array of date fields selected by cfg (Config)
the cal’s configuration object
Script: the current action (e.g.,
var myCal = new YAHOO.widget.Calendar("container"); [[2008,8,1],[2008,8,2]]) oDomContainer (el)
the cal’s outer container
myCal.render(); Array of date fields deselected by
deselectEvent After a date has been
deselected. the current action (e.g., YAHOO.widget.Calendar &
Creates a single page Calendar instance set to the current month. [[2008,8,1],[2008,8,2]])
CalendarGroup Methods
changePageEvent When the Calendar none
Constructor: YAHOO.widget.Calendar, CalendarGroup navigates to a new Navigation:
month. addMonths(int)
YAHOO.widget.Calendar([str calId,] str|HTMLElement
container [,obj config]); showEvent When the Calendar’s none addYears(int)
show() method is called. subtractMonths(int)
YAHOO.widget.CalendarGroup([str calId,] str|HTMLElement subtractYears(int)
container [,obj config]); hideEvent When the Calendar’s none setMonth(int)
hide() method is called. setYear(int)
Arguments: All Calendar events are Custom Events (see Event Utility docs); subscribe to these events nextMonth()
using their subscribe method: myCal.selectEvent.subscribe(fnMyHandler);. nextYear()
(1) calId: HTML ID for the new element created by the control to house the
Event-specific arguments, if present, will be passed in an array as the second argument to previousMonth()
Calendar's DOM structure (optional, as of 2.4.0). If not provided, the the event handler. Some events also have a "before" event which can be subscribed to previousYear()
container’s ID with a “_t” suffix is used.
(2) container: HTML ID of (or a reference to) an existing but empty HTML Rendering:
element into which the new Calendar will be inserted. Calendar Options
Configure options using the constructor configuration object or setProperty, as described in “Solutions” render()
(3) config: Calendar configuration settings object (optional). renders current state to page
Calendar objects include several configurable options, including: addRenderer
(s dates, fn renderer)
Solutions SHOW_WEEKDAYS SHOW_WEEK_ HEADER MULTI_SELECT
addWeekdayRenderer
(int wkd, fn renderer)
Render a single page calendar set displaying January 2008 with Spanish HIDE_BLANK_WEEKS PAGES (CalendarGroup only) NAVIGATOR addMonthRenderer
weekdays and month names: (int month, fn renderer)
Localizing Calendar and CalendarGroup show()
myCal = new YAHOO.widget.Calendar("container", hide()
{ pagedate: "1/2008", Calendar instances can be localized via configuration options, including:
MONTHS_LONG:["Jenero","Febrero", … ,"Diciembre"], Selection:
WEEKDAYS_SHORT:["Lu", "Ma", … , "Do"]}); MONTHS_SHORT WEEKDAYS_1CHAR WEEKDAYS_MEDIUM select(str date)
myCal.render(); MONTHS_LONG WEEKDAYS_SHORT WEEKDAYS_LONG selectCell(int cellIdx)
LOCALE_MONTHS LOCALE_WEEKDAYS deselect(str date)
Add highlighting for Mexican holidays using CSS styles: deselectCell(int cellIdx)
<style> deselectAll()
Applying localization properties requires the same syntax as any other
.m1 .d1, .m1 .d6, .m2 .d5, .m2 .d14, .m2 .d24
properties in a Calendar’s cfg object: getSelectedDates()
{ background-color:yellow; } returns array of JS date objects
</style> myCal = new YAHOO.widget.Calendar("calEl", "container"); clear()
myCal.cfg.setProperty("MONTHS_SHORT", removes all selected dates,
There are two ways to configure options on your Calendar: ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", resets month/year
"Sep", "Okt", "Nov", "Dez"] );
// 1. In the constructor, via an object literal: Other:
myCal.cfg.setProperty("LOCALE_MONTHS", "short");
myCal = new YAHOO.widget.Calendar("container", myCal.render(); reset()
{pagedate: "5/2008"}); resets calendar to original state
// 2. Via "setProperty" after rendering: myCal.cfg.setProperty
myCal.cfg.setProperty("pagedate", "5/2008"); Dependencies (propName, propValue)
myCal.cfg.getProperty
Calendar requires the YAHOO Object, Event, and Dom. (propName)
YUI Library: Carousel 2009-2-6 2.7
Simple Use Case: YAHOO.widget.Carousel Interesting Moments in Carousel YAHOO.widget.Carousel
See online docs for complete list of Carousel events. containerId (str)
Markup: cfg (Config)
<div id="container"><ul><li>item</li></ul></div> Event Fires... Passes back:
the carousel’s configuration object
afterScroll After the viewport in the The indices of the first
Script: Carousel has scrolled. and last items in the YAHOO.widget.Carousel
var carousel = new YAHOO.widget.Carousel("container"); viewport. Methods
carousel.render();
itemAdded After an item has been The content of the Manipulation:
Creates a simple Carousel of items added to the Carousel. inserted item and the
addItem(String, index)
inside the list container (UL). position where it is
addItems(array)
inserted.
clearItems()
Carousel ships with a skin (left) that pageChangeEvent When the Carousel Page number of the removeItem(int)
provides visual elements for the navigates to a new page. current page.
navigation controls. Apply the CSS
class yui-skin-sam to the body navigationStateChange When the state of the The state of the Navigation:
element or other parent element of navigation buttons change navigation buttons scrollBackward()
your Carousel’s container in order to (enabled/disabled). (true if enabled, false scrollForward()
make use of the default skin. otherwise) scrollTo(int)
loadItems When the Carousel needs The first and last
more items to be loaded visible items in the Rendering:
for displaying them. Carousel and the render([String])
renders current state to page
number of items to be
loaded. show()
hide()
All Carousel events are Custom Events (see Event Utility docs); subscribe to these events
using their subscribe method: carousel.loadItems.subscribe(fnMyHandler);. Selection:
Event-specific arguments, if present, will be passed in an array as the second argument to
the event handler. Some events also have a before event to which you can subscribe.
set(“selectedItem”, int)

Other:
Constructor: YAHOO.widget.Carousel Solutions resets calendar to original state
carousel.set
YAHOO.widget.Carousel([str container,] [,obj config]); Basic markup for a Carousel:
(propName, propValue)
Arguments: <div id="container"> carousel. get
(1) container: HTML ID or HTMLElement of existing markup to use <ul> (propName)
<li><img alt="" src="..."></li>
when building Carousel. This should be a UL or an OL element. </ul>
(2) Configuration Object: JS object defining configuration properties </div>
for the Carousel instance. See Configuration section and online
Render a Carousel that scrolls automatically every two seconds and animating
docs for a list of these options.
while scrolling:
carousel = new YAHOO.widget.Carousel("container", {
Carousel Options autoPlay: 2000, animation: { speed: 0.5 }
Configure options using the constructor configuration object or set(), as described in “Solutions” });
carousel.render();
Carousel objects include several configurable options, including:
There are two ways to configure options on your Carousel:
animation isCircular numVisible
autoPlay isVertical revealAmount // 1. In the constructor, via an object literal:
carousel = new YAHOO.widget.Carousel("container", {
isCircular: true
Dependencies });
Carousel requires YAHOO, Dom, Event and Element. // 2. Via "set":
carousel.set("isCircular", true);
YUI Library: Charts 2009-2-6 v2.7
Simple Use Case: YAHOO.widget.LineChart Key Interesting Moments in Charts YAHOO.widget.Axis
See online docs for a complete list of Charts Events. Properties
Markup: Event: Arguments: type
itemClickEvent, args.type (String) orientation
<div id="myContainer"> itemDoubleClickEvent, args.item (Object) reverse
<-- For progressive enhancement, it’s best to put itemMouseOverEvent, args.index (Number) labelFunction
the chart’s data here in tabular or textual form to itemMouseOutEvent args.seriesIndex (Number) hideOverlappingLabels
support viewers with Flash disabled. --> args.x (Number)
</div> args.y (Number) YAHOO.widget.NumericAxis
Script: itemDragStartEvent, args.type (String) Properties
itemDragEvent, args.item (Object) minimum
var mySeriesDef = [
itemDragUpdateEvent args.index (Number) maximum
{yField: "field1", displayName: "Series 1"},
{yField: "field2", displayName: "Series 2"}, args.seriesIndex (Number) majorUnit
...]; args.x (Number) minorUnit
var myDataSource = args.y (Number) snapToUnits
new YAHOO.util.DataSource([...]); alwaysShowZero
var myChart = new YAHOO.widget.LineChart( All Charts events are Custom Events (see Event Utility docs); subscribe to these events scale
"myContainer", myDataSource, {} ); using “subscribe”: (e.g. myChart.subscribe("itemClickEvent", handler); ).
Note: Refer to online documentation for
a full list of Axis properties.
Creates a Chart instance from scratch. Key Charts Configuration Options
See online docs for complete list of Charts configuration options. YAHOO.widget.Series
Option (type) Default Description Properties
xField (s) null The field used to access data to position
yField (s) items along the x or y axis. type
request (s) "" Request value to send to DataSource at displayName
instantiation for data to populate the chart.
series (a) null A series definition object. YAHOO.widget.CartesianSeries
dataTipFunction see docs Object literal of pagination values. Properties
(s)
Constructor: YAHOO.util.DataSource xAxis (o) null Custom axis objects. xField
yAxis (o) yField
YAHOO.util.DataSource(str|array|obj|HTMLFunction
|HTMLTable live data[, obj config]); polling (n) null The number of milliseconds between
requests to the DataSource object for new YAHOO.widget.PieSeries
Arguments: data. Properties
(1) live data: Pointer to a set of data. categoryNames (a) null If the DataSource does not contain a field
that may be used with a category axis, an dataField
(2) configuration object: An optional object literal defines property categoryField
values of a DataSource instance. Array of Strings may be substituted.
dataSource null Replace the current DataSource Note: Refer to online documentation for
a full list of Series properties.
wmode “window” The window mode of Flash Player. May be
Constructor: YAHOO.widget.ColumnChart “window”, “opaque” or “transparent”.
YAHOO.widget.ColumnChart(str element, obj DataSource[,
Charts options can be set in the constructor's third argument (e.g., {xField: "month"}) or at Dependencies
runtime via set (e.g., myChart.set("xField", "month");).
obj config]);
Charts require the YAHOO
Arguments: Solutions Global Object, Event Utility,
Dom Collection, Element
(1) element: HTML ID for a Chart container. May be empty or contain Specify a custom axis dimension if you don’t want the chart to size the axis by Utility, JSON Utility and
alternative content. default: DataSource Utility. Note:
(2) DataSource: DataSource instance.
On the client, Charts
(3) configuration object: An optional object literal defines property var axisWithMinimum = new YAHOO.widget.NumericAxis(); requires Flash Player 9.0.45
values of a Chart instance. axisWithMinimum.minimum = 800; or later.
myChart.set( "yAxis", axisWithMinimum );
YUI Library: Color Picker Control 2009-2-6 v2.7
Simple Use Case: YAHOO.widget.ColorPicker Interesting Moment in Color Picker YAHOO.widget.ColorPicker:
This is the full list of Custom Events exposed in the Color Picker API. Methods
Markup: Event: Event Fields:
<div id="picker"></div> getElement(id | key element)
rgbChange newValue (arr) and oldValue (arr), in both cases an returns the requested element; see API docs
Script: array of RGB values; type (s), "rgbChange". for keyset…pass in YUI_PICKER to return
the host element for the instance
var oPicker = new All Color Picker events are Custom Events (see Event Utility docs); subscribe to these events setValue(arr RGB[, b silent]) sets
YAHOO.widget.ColorPicker("picker", { using “addListener” or "on": (e.g. oPicker.on('rgbChange', fn); ). the currently selected color
showhsvcontrols: true,
showhexcontrols: true Key Color Picker Configuration Options YAHOO.widget.
); See online docs for complete list of Color Picker configuration options.
Option (type) Default Description ColorPicker: Form Fields
Creates a Color Picker instance from script; the Color Picker's
DOM structure is created in the element whose ID is "picker". showcontrols (b) true Hide/show the entire set of controls. When a form wrapping a Color Picker
instance is submitted, the following
showhexcontrols (b) true Hide/show the hex controls. form fields are included:
showhexsummary (b) true Hide/show the hexadecimal
summary information. yui-picker-r RGB red
yui-picker-g RGB green
showhsvcontrols (b) false Hide/show the HSV controls.
yui-picker-b RGB bluee
showrgbcontrols (b) true Hide/show the RGB controls. yui-picker-h HSV hue
showwebsafe (b) true Hide/show the websafe swatch. yui-picker-s HSV
images (o) Default Object Members: saturation
images PICKER_THUMB: Image
served by
yui-picker-v HSV value/
Y! servers representing the draggable thumb brightness
for the color region slider. yui-picker- Hex triplet for
HUE_THUMB: Image representing hex current color
the draggable thumb for the HSV
slider. Dependencies
Color Picker options can be set in the constructor's second argument (eg,
{showwebsafe: false}) or at runtime via set (eg, oPicker.set("showwebsafe", Color Picker requires
Constructor: YAHOO.widget.ColorPicker false);). Yahoo, Dom, Event,
Element, Drag & Drop,
YAHOO.widget.ColorPicker(str ID|HTMLElement Solutions and Slider. For the
element[, obj config]);
richest interaction, the
Arguments: Listen for the rgbChange event and make use of the event's fields:
optional Animation
(1) Element: HTML ID or HTMLElement for container element; var oPicker = new Utility is highly
this is the location in the DOM where the Color Picker Control YAHOO.widget.ColorPicker("container"); recommended.
will be inserted. //a listener for logging RGB color changes;
(2) Configuration Object: JS object defining configuration //this will only be visible if logger is enabled:
properties for the Color Picker instance. See Configuration var onRgbChange = function(o) {
Options section for full list. /*o is an object
{ newValue: (array of R, G, B values),
Setting the Color Picker's Value prevValue: (array of R, G, B values),
type: "rgbChange"
You can set the Color Picker's current value by script any time }
after instantiation using setValue: */
YAHOO.log("The new color value is " + o.newValue,
oPicker.setValue([255, 255, 255], false);
"info", "example");
The second argument is a boolean; if true, it suppresses the }
rgbChange event that would otherwise be fired when the value is //subscribe to the rgbChange event;
changed. oPicker.on("rgbChange", onRgbChange);
YUI Library: Connection Manager 2009-2-13 v2.7
Simple Use Case Global Custom Events Key methods of
These events fire for all transactions; subscribe via YAHOO.util.Connect; e.g.: YAHOO.util.Connect:
var callback = { YAHOO.util.Connect.startEvent.subscribe(myFn);
(o = Transaction object)
success: function(o) {
document.getElementById(‘someEl’).innerHTML = Event Fires when... Arguments abort(o)
o.responseText; startEvent transaction begins transaction ID asyncRequest()
} initHeader(s label, s
} completeEvent transaction complete, but not yet transaction ID
reconciled as success or failure value, [b persistHeader])
optional param persists header as a
var connectionObject = default for each subsequent
YAHOO.util.Connect.asyncRequest('GET', ‘file.php’, successEvent HTTP 2xx response received Response object
transaction.
callback); failureEvent HTTP 4xx, 5xx, or unknown Response object isCallInProgress(o)
response received setForm(str formId | o
Executes an asynchronous connection to file.php. If the HTTP status of the
response indicates success, the full text of the HTTP response is placed in a abortEvent timeout/abort succeeds transaction ID form el ref[, b isUpload,
page element whose ID attribute is “someEl”. s secureUri]) optional params
Response Object for file upload only; provide secureUri
for iFrame only under SSL

Invocation (asyncRequest) Your success, failure, and upload handlers are passed a single argument; that argument setPollingInterval(int i)
is an object with the following members: setProgId(id)
YAHOO.util.Connect.asyncRequest(str http method, str url[, tId The transaction id.
obj callback object, str POST body]); status The HTTP status code of the request. HTTP Status Codes
Arguments: statusText The message associated with the HTTP status.
getResponse Array collection of response headers and their corresponding
(1) HTTP method (string): GET, POST, HEAD, PUT, DELETE, etc. PUT and 2xx Successful
Header[] values, indexed by header label.
DELETE are not supported across all A-Grade browsers. getAllResponse String containing all available HTTP headers with name/value pairs 3xx Redirection
(2) URL (string): A url referencing a file that shares the same server DNS Headers delimited by "\n". 4xx Client error
name as the current page URL. responseText The server’s full response as a string; for upload, the contents of
(3) Callback (object): An object containing success and failure handlers and the response's <body> tag. 5xx Server error
arguments and a scope control; see Callback Object detail for more. responseXML If a valid XML document was returned and parsed successfully by
(4) POST body (string): If you are POSTing data to the server, this string holds the XHR object, this will be the resulting DOM object. 0 Communication
the POST message body. argument The arguments you defined in the Callback object's argument failure
Returns: Transaction object. { tId: int transaction id } The member.
200 OK
transaction object allows you to interact (via Connection Manager) with your
400 Bad request
XHR instance; pass tId to CM methods such as abort(). Solutions 401 Unauthorized
403 Forbidden
Callback Object: Members (All Optional) Roll up an existing form on the page, posting its data to the server:
404 Not found
YAHOO.util.Connect.setForm('formId');
1. customevents: Object containing any Custom Event handlers for var cObj = YAHOO.util.Connect.asyncRequest('POST',
408 Request timeout
transaction-level events (as alternatives to success and failure handlers 'formProcessor.php', callback); 410 Gone
below). Transaction-level Custom Events include onStart, onComplete, 500 Internal server
onSuccess, onFailure, onAbort and receive the same arguments as their Cancel a transaction in progress:
error
global counterparts (see Global Custom Events, above right). //if the transaction is created as follows... 502 Bad gateway
2. success (fn): The success method is called when an asyncRequest is var cObj = YAHOO.util.Connect.asyncRequest(‘GET’,
replied to by the server with an HTTP in the 2xx range; use this function to myServer.php', callback); 503 Service unavailable
process the response. //...then you would attempt to abort it this way:
3. failure (fn): The failure method is called when asyncRequest gets an YAHOO.util.Connect.abort(cObj);
HTTP status of 400 or greater. Use this function to handle unexpected
Connection Manager sets headers automatically for GET and POST
application/communications failures.
transactions. If you need to set a header manually, use this syntax:
4. argument (various): The argument member can be an object, array,
integer or string; it contains information to which your success and failure YAHOO.util.Connect.initHeader('SOAPAction', 'myAction');
handlers need access.
5. scope (obj): The object in whose scope your handlers should run.
6. timeout (int): Number of milliseconds CM should wait on a request before Dependencies
aborting and calling failure handler. Connection Manager requires the YAHOO Global Object and the Event Utility.
7. upload (fn): Handler to process file upload response.
YUI Library: Cookie Utility 2009-2-6 v2.7
Simple Use Case: Reading/writing a cookie Cookie Options Object YAHOO.util.Cookie
Options that can be set on the options object in remove(), set(), removeSub(), setSub(), and setSubs(). Cookie Methods
var value = YAHOO.util.Cookie.get("name"); Member Type Description get(str name, func converter) returns
expires Date A Date object representing the date and time at which a cookie value
Retrieves the cookie named “name” and stores its value in a the cookie should expire. set(str name, str value, obj options)
sets a cookie
variable. domain string The domain for which the cookie should be accessible. remove(str name, obj options) removes
path string The path for which the cookie should be accessible. a cookie
YAHOO.util.Cookie.set("name", "value"); secure boolean Indicates if the cookie is accessible only via SSL.
YAHOO.util.Cookie
Sets a cookie named “name” and stores “value” in it. Usage: YAHOO.util.Cookie.getSub() Subcookie Methods
var value = YAHOO.util.Cookie.getSub(str name, str getSub(str name, str subname, func
Usage: YAHOO.util.Cookie.get() subname [, func converter])
converter) returns a subcookie value
getSubs(str name) returns all subcookies
in an object
var value = YAHOO.util.Cookie.get(str name[, Arguments: setSub(str name, str subname, str
func converter]) (1) name: The name of the cookie to get. value, obj options) sets a subcookie
Arguments: (2) subname: The subcookie name to get. setSubs(str name, obj subcookies,
obj options) sets all subcookies in a
(1) name: The name of the cookie to get. (3) converter: (Optional) A conversion function to run the value through cookie
(2) converter: (Optional) A conversion function to run the value before returning it. This function is not called if the subcookie with the removeSub(str name, str subname,
through before returning it. This function is not called if the given name doesn’t exist. obj options) removes a subcookie

cookie with the given name doesn’t exist.


Usage: YAHOO.util.Cookie.removeSub() Dependencies
Usage: YAHOO.util.Cookie.remove() YAHOO.util.Cookie.removeSub(str name, str subname [, The Cookie utility requires
obj options]) only the YAHOO Global
YAHOO.util.Cookie.remove(str name, [, obj object.
options]) Arguments:
Arguments: (1) name: The name of the cookie in which the subcookie exists.
(1) name: The name of the cookie to set. (2) subname: The subcookie name to remove.
(2) options: (Optional) Options indicating setting the accessibility (3) options: (Optional) Options indicating setting the accessibility of the
of the cookie. These settings should be the same as the ones cookie. These settings should be the same as the ones used to set
used to set the cookie. the cookie.

Usage: YAHOO.util.Cookie.set() Usage: YAHOO.util.Cookie.setSub()

YAHOO.util.Cookie.set(str name, str value [, obj YAHOO.util.Cookie.setSub(str name, str subname, str
options]) value [, obj options])

Arguments: Arguments:
(1) name: The name of the cookie to set. (1) name: The name of the cookie to set.
(2) value: The value of the cookie to set. (2) subname: The subcookie name to set.
(3) options: (Optional) Options for setting the accessibility of the (3) value: The value for the subcookie.
cookie based on expiration date, domain, path, and security. (4) options: (Optional) Options for setting the accessibility of the cookie
based on expiration date, domain, path, and security.
YUI Library: CSS Reset, Base, Fonts, and Grids 2009-2-6 v2.7
Recommended Doctype and Render Mode YUI CSS Grids: Nomenclature Fonts Sizing Chart
#doc – Define the overall width of the page. For Use this
YUI works in both “Quirks” and “Standards/Strict” browser-
#doc4 doc 750px, doc2 950px, doc3 100%, doc4 974px, this PX percentage:
rendering modes, but we suggest using Standards mode by
.yui-t1 – Six preset template for secondary column size & side. 10 77
specifying this Doctype:
.yui-t6 (see right column, bottom chart) 11 85
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN” .yui-g Basic grid (.yui-g) tells two units (.yui-g) to share. 12 93
“http://www.w3.org/TR/html4/strict.dtd”> 13 100
.yui-gb – Special grids (.yui-gb ... .yui-gf) are for three-
14 108
.yui-gf unit and uneven two-unit space sharing. 15 116
YUI CSS Reset + YUI CSS Base (see right column, middle chart) 16 123.1
.yui-u A unit inside a grid; generic; obeys parent grid. 17 131
YUI CSS Reset neutralizes browser CSS styles for HTML
elements, creating a normalized platform. YUI CSS Base then .first Overload the class attribute with “first” to indicate first 18 138.5
rebuilds a consistent style foundation for common HTML elements. of a series of grids or units. (This facilitate floats and 19 146.5
margins.) 20 153.9
YUI CSS Base is also useful as a snippets library, for instance to
21 161.6
see how to put bullets back on UL LIs.
Customize Page Width 22 167
23 174
YUI CSS Fonts: Setting Font Size and Family Pixels / 13 = width in ems. For IE, pixels / 13.333. Use star- 24 182
property filter to target IE. For example, this sets 610px: 25 189
Font-size: While still allowing users to zoom their font sizes, the #custom-doc { 26 197
YUI Fonts package renders all text at 13px by default. To preserve width:46.923em; /* 610/13 */
users’ ability to zoom their fonts, specify other sizes using *width:45.750em;/* 610/13.3333 */ Grids: Nesting Grids
percentages only (see top chart in right column). } (yui-g’s)
selector {font-size:123.1%;} /*16px*/ .yui-g 1/2, 1/2
Font-family: The YUI Fonts package defines Arial as the default
The Basic Grid Pattern .yui-gb 1/3, 1/3, 1/3
font and provides a degradation path through several alternate <div class="yui-g">
.yui-gc 2/3, 1/3
fonts down to the generic “sans-serif.” When specifying other font <div class="yui-u first"></div> .yui-gd 1/3, 2/3
families, provide your own degradation path as needed. <div class="yui-u"></div> .yui-ge 3/4, 1/4
</div> .yui-gf 1/4, 3/4
<style>selector {font-family:verdana,sans-
serif;}</style> Other configurations, such
as !, !, !, ! can be
The Nested Grid Pattern
rendered by nesting yui-g’s
Base Page Format <div class="yui-g"> inside other “yui-g” grids.
We find it useful to build a page in three stacked horizontal regions: <div class="yui-g first">
<div class="yui-u first"></div> Grids: Templates
<body> <div class="yui-u"></div>
<div id=”doc”><!—-overall document wrapper--> (yui-t’s)
</div>
<div id=”hd”><!--header / masthead--></div> <div class="yui-g"> .yui-t1 160 on left
<div id=”bd”><!--body--></div> <div class="yui-u first"></div> .yui-t2 180 on left
<div id=”ft”><!--footer--></div> <div class="yui-u"></div>
</div>
.yui-t3 300 on left
</div>
</body> .yui-t4 180 on right
</div>
.yui-t5 240 on right
Inside #bd, if two blocks (.yui-b) exist, designate a main block by .yui-t6 300 on right
wrapping it with <div id=”yui-main”>:
<div id=”yui-main”>
<div class=”yui-b”><!--primary--></div>
</div>
<div class=”yui-b”><!--secondary--></div>
YUI Library: DataSource 2009-2-17 v2.7
Simple Use Case Interesting Moments YAHOO.util.
Event oArgs passed to handler
DataSourceBase
Script: Properties:
var myDataSource = new YAHOO.util.DataSource cacheFlushEvent none
([{name:"a",id:"1"}, {name:"b",id:"2"}]); oArgs.request {obj} The request object dataType (int)
myDataSource.responseType = cacheRequestEvent
oArgs.callback {obj} The callback object liveData (mixed)
YAHOO.util.DataSource.TYPE_JSARRAY;
oArgs.request {obj} The request object responseSchema (obj)
myDataSource.responseSchema = [fields:["name","id"];
cacheResponseEvent oArgs.response {obj} The response object responseType (int)
Instantiates a new DataSource object, myDataSource, which manages data oArgs.callback {obj} The callback object
retrieval for use by other widgets. oArgs.request {obj} The request object YAHOO.util.XHRDataSourc
dataErrorEvent oArgs.callback {obj} The callback object e Properties:
Constructors oArgs.message {str} Error message
connMethodPost (b)
oArgs.request {obj} The request object
YAHOO.util.LocalDataSource(mixed data[, obj connMgr
configurations]); requestEvent oArgs.callback {obj} The callback object
(YAHOO.util.Connectio
oArgs.tId {int} Unique transaction ID
(1) data (array): A JavaScript array of strings. n)
oArgs.request {obj} The request object
(2) Configuration object (object): An optional object literal defines property connTimeout (int)
values of a DataSource instance. responseCacheEvent oArgs.response {obj} The response object
connXhrMode
oArgs.callback {obj} The callback object
YAHOO.util.FunctionDataSource(fn function[, obj ("queueRequests" |
configurations]); oArgs.request {obj} The request object "cancelStaleRequests" |
oArgs.response {obj} The response object ignoreStaleResponses"
(1) JS Function (fn): A JavaScript function which returns an array of strings. responseEvent
oArgs.callback {obj} The callback object | "allowAll")
(2) Configuration object (object): See above.
oArgs.tId {int} Unique transaction ID
YAHOO.util.ScriptNodeDataSource(str uri[, obj oArgs.request {obj} The request object
configurations]); YAHOO.util.ScriptNodeDat
responseParseEvent oArgs.response {obj} The response object
(1) URI: URI to the script location that will return data. oArgs.callback {obj} The callback object
aSource Properties:
(2) Schema (array): Schema description of server response data. Subscribe to DataSource Custom Events on your DataSource instance: asyncMode
(3) Configuration object (object): See above. myDS.subscribe("requestEvent", myFn); ("ignoreStaleResponse
YAHOO.util.XHRDataSource(str uri[, obj configurations]); s" | "allowAll")
Abstract Methods getUtility
(1) Script URI (string): Server URI (local domains only – use a proxy for
remote domains). Method Description (YAHOO.util.Get)
(2) Schema (array): Schema description of server response data. This overridable abstract method gives scriptCallbackParam
(3) Configuration object (object): See above. implementers an opportunity to access the (str)
YAHOO.util.DataSource(mixed data[, obj configurations]); data before it has been cached or returned
doBeforeCallback
to the callback. Implementers should be
(1) Script URI (string): Server URI (local domains only – use a proxy for
sure to return data in a ready-to-return state
remote domains).
(2) Schema (array): Schema description of server response data. to avoid errors.
(3) Configuration object (object): See above. This overridable abstract method gives
implementers an opportunity to munge the
doBeforeParseData data before it is schema-parsed.
Key Configuration Properties
Implementers should be sure to return data
Property Description in a ready-to-parse state to avoid errors.
Determines which parsing algorithm to
responseType
use on response data. Dependencies
Determines what data gets parsed out
responseSchema DataSource requires the YAHOO Global Object and the Event Utility.
of response for consumption.
Connection Manager (for XHRDataSource), the Get Utility (for
ScriptNodeDataSource), and the JSON Utility (for JSON data) are
optional.
YUI Library: DataSource 2009-2-17 v2.7
Data Flow in DataSource
YUI Library: DataTable 2009-2-6 v2.7
Simple Use Case: YAHOO.widget.DataTable Key Interesting Moments in DataTable YAHOO.widget.Column:
Not all event types are available for all elements and units. See online docs for full list of DataTable Events. Properties
Markup (container can be empty or pre-populated for progressive Event oArgs Properties
enhancement): abbr
elementClickEvent, oArgs.event (HTMLEvent) children
<div id="myContainer"><div> elementDblclickEvent, oArgs.target (el)
className
elementMousedownEvent,
Script: elementMouseoutEvent, An element is a DOM element, such as button, cell, row, theadCell, editor
elementMouseoverEvent theadLabel, etc. formatter
var myColumnDefs = [{key:"col1", label:"Col 1"}, unitHighlightEvent, oArgs.el (el) hidden
{key:"col2", label:"Col 2"}, ...]; unitSelectEvent, oArgs.record (YAHOO.widget.Record) key
var myDS = new YAHOO.util.DataSource([...]); unitUnhighlightEvent, label
When unit is a cell:
unitUnselectEvent, maxAutoWidth
var myDataTable = new YAHOO.widget.DataTable( cellFormatEvent
oArgs.key (string)
"myContainer", myColumnDefs, myDS); minWidth
A unit is a cell, row, or column.
columnSortEvent oArgs.column (YAHOO.widget.Column) resizeable
oArgs.dir (string) YAHOO.widget.DataTable.CLASS_ASC || selected
Constructor: YAHOO.widget.DataTable YAHOO.widget.DataTable.CLASS_DESC sortable
editorRevertEvent, oArgs.editor (object), oArgs.newData (object), sortOptions.defaultDir
YAHOO.widget.DataTable(str|HTMLElement el, array editorSaveEvent oArgs.oldData (object) sortOptions.sortFunction
column defs, obj DataSource[, obj config]); initEvent, renderEvent n/a width
rowAddEvent oArgs.record (YAHOO.widget.Record)
Arguments: rowDeleteEvent oArgs.oldData (object) YAHOO.widget.ScrollingData
(1) el: HTML ID or HTMLElement for a DataTable container. May be
empty or already contain <table> markup.
oArgs.recordIndex (number) Table Key Attributes
oArgs.trElIndex (number)
(2) column defs: An array of object literals defines Columns. rowUpdateEvent oArgs.record (YAHOO.widget.Record) COLOR_COLUMNFILLER
(3) DataSource: DataSource instance. oArgs.oldData (object) height
(4) configuration object: An optional object literal defines property All DataTable events are Custom Events (see Event Utility docs); subscribe to these events width
values of a DataTable instance. using “subscribe”: (e.g. myDataTable.subscribe("rowSelectEvent", fn); ).
YAHOO.widget.BaseCellEdito
Key DataTable Attributes r Subclasses
Constructor: YAHOO.widget.ScrollingDataTable
Option (type) Default Description CheckboxCellEditor
YAHOO.widget.ScrollingDataTable(str|HTMLElement caption (s) null String values for caption element and summary DateCellEditor
el, array column defs, obj DataSource[, obj summary (s) null attribute.
DropdownCellEditor
draggableColumns (b) false Enables Drag & Drop Column reordering.
config]); RadioCellEditor
initialLoad (b|o) true Enables or customizes data load at instantiation.
initialRequest (mixed) null Request value to send to DataSource at
TextareaCellEditor
Arguments: TextboxCellEditor
instantiation for data to populate the table, if
(1) el: HTML ID or HTMLElement for a DataTable container. May be initialLoad is set to true. Note: Refer to online documentation for a
empty or already contain <table> markup. paginator (o) null Instance of YAHOO.widget.Paginator. complete API reference.
(2) column defs: An array of object literals defines Columns. renderLoopSize 0 Number of rows to render into the DOM each
(3) DataSource: DataSource instance. timeout loop.
(4) configuration object: An optional object literal defines property scrollable (b) false Enables scrolling. Dependencies
values of a DataTable instance, including width and height of width (s)/height (s) null
scrollable area. selectionMode (s) "standard" Configures row or cell selection. DataTable requires the
sortedBy (o) null Displays sorted Column UI. YAHOO Global Object, Event
Utility, Dom Collection,
Cell Editing Abstract Methods Element Utility, and
DataSource Utility.
var myCE = new YAHOO.widget.TextboxCellEditor; Method Description
var myColumnDefs = [{key:"col1}, {key:"col2", doBeforeLoadData Overridable method gives implementers a hook to access data
before it gets added to RecordSet and rendered to the TBODY.
editor: myCE];
...
myDT.subscribe("cellClickEvent",
doBeforeShowCellEditor Overridable abstract method to customize CellEditor before
myDT.onEventShowCellEditor) showing.
doBeforeSortColumn Overridable method gives implementers a hook to show
loading message before sorting Column.
YUI Library: Dialog & SimpleDialog 2009-2-6 v2.7
Simple Use Case: YAHOO.widget.Dialog Key Interesting Moments in Dialog & SimpleDialog YAHOO.widget.Dialog &
See online docs for a complete list of Custom Events associated with Container controls. SimpleDialog: Key
Markup (optional, using HTML form in standard module format): Event Arguments Properties
<div id="myDialog"> beforeSubmitEvent None. body (el)
<div class="bd"> cancelEvent None. form (el)
<form name="dlgForm" method="POST" action=" submitEvent None. callback (o) Connection
post.php"> All events above are YUI Custom Events (see Event Utility docs); subscribe to these Manager callback object for
<label for="firstname">First Name:</label> events using their subscribe method: myDlg.hideEvent.subscribe(fnMyHandler);. async transactions.
<input type="text" name="firstname" /> element (el) containing
Dialog/SimpleDialog Configuration Options
header, body & footer
</form></div>
</div> footer (el)
See online docs for complete list of Container options; see Simple Use Case (top left) for config. syntax.
header (el)
Script: Option (type) Default Description id (s) of the element
text null Sets body text of SimpleDialog
//create the dialog:
(SimpleDialog only). YAHOO.widget.Dialog &
var myDialog = new YAHOO.widget.Dialog("myDialog");
icon “none” Sets url for graphical icon. Six icons SimpleDialog: Methods
//set dialog to use form post on submit action:
myDialog.cfg.queueProperty(“postmethod”, “form”); are provided: ICON_BLOCK,
ICON_WARN, ICON_HELP, appendToBody(el
//set up button handler:
ICON_INFO, ICON_ALARM, and element)
var handleSubmit = function() {
ICON_TIP. (SimpleDialog only.) appendToFooter(el
this.submit(); }; //default submit action
//set up button, link to handler postmethod (s) varies Designates handling of form data; see element)
var myButtons = [ { text:"Submit", box at bottom left. Default is “none” for appendToHeader(el
handler:handleSubmit, isDefault:true } ]); SimpleDialog and “async” for Dialog. element)
//put buttons in configuration queue for processing buttons (a) null Array of button objects. Button objects cancel() Executes cancel then
hide().
myDialog.cfg.queueProperty("buttons", myButtons); contain three members: text label for
getData() Returns obect of
mDialog.render(); //render dialog to page button, handler function to process name/value pairs representing
myDialog.show(); //make dialog visible button click, and isDefault boolean form data.

specifying whether this is the default hide()


Creates, renders and shows a panel using existing markup and all render([el element])
default Dialog settings. action on form submit. Argument required for Dialogs
See cheat sheet for Panel for additional configuration options; see online documentation not built from existing markup.
for full list. Dialog will not be in the DOM or
Constructor: YAHOO.widget.Dialog & SimpleDialog visible until render is called.
Solutions setBody(str or el
YAHOO.widget.Dialog(str elId[, obj config]); content)
Use validate() to check form data prior to submitting: setFooter(str or el
Arguments:
(1) Element ID: HTML ID of the element being used to create the fnCheckEmail = function() { content)
Dialog or SimpleDialog. If this element doesn't exist, it will be if (myDialog.getData().email.indexOf(“@”) > -1) setHeader(str or el
created. {return true;} else {return false;} }; content)
(2) Configuration Object: JS object defining configuration properties myDialog.validate = fnCheckEmail; submit() Executes submit
followed by hide().
for the Dialog. See Configuration section for full list. Set “success” handler for asynchronous post: show()
fnSuccess = function(o) {//function body}; getButtons()
The postmethod Property: Dialog & SimpleDialog myDialog.callback.success = fnSuccess;
postmethod: Characteristics:
“none” Button handlers do all form processing. Dependencies
“form” Button handlers called, then form posted to url designated
in form’s target attribute. Dialog requires the full Container package, the Yahoo Object, Dom
“async” Button handlers called, then form sent to url designated in Collection, and Event Utility. Animation, Button, Connection Manager
form’s target attribute using asynchronous and Drag And Drop are optional (though required for specific features).
XMLHttpRequest (via Connection Manager).
YUI Library: Dom Collection 2009-2-6 v2.7
Methods Reference Methods Reference (continued) Useful Dom Methods:
Returns: Method: Returns: Method: appendChild()
void addClass (str | el ref | arr el, str className) b/array hasClass (str | el ref | arr el, str className) click()
Adds a class name to a given element or collection of elements Determines whether the element(s) has the given className. cloneNode()
obj/array batch (str | el ref | arr el, fn method, any o, b overrideScope) b/array inDocument (str | el ref | arr el) createElement()
Returns the element(s) that have had the supplied method Determines whether the element(s) is present in the current createTextNode()
applied. The method will be provided the elements one at a document. focus()
time (method(el, o)). obj insertAfter (str | el ref newNode, str| el ref refNode) getAttribute()
str/array generateId (str | el ref | arr el, str prefix) Inserts the newNode as the next HTMLElement sibling of the
getElementById()
Generates a unique ID for the specified element. refNode.
obj/array get (str | el ref | arr el) obj insertBefore (str | el ref newNode, str| el ref refNode)
getElementsBy
Returns an HTMLElement object or array of objects. Inserts the newNode as the previous HTMLElement sibling of TagName()
int getViewportHeight () the refNode. hasAttribute()
Returns the height of the client (viewport). b isAncestor (el ref haystack, el ref needle) hasChildNodes()
int getViewportWidth () Determines whether an HTMLElement is an ancestor of another insertBefore()
Returns the width of the client (viewport). HTMLElement in the DOM hierarchy. removeAttribute()
obj getAncestorByTagName (str | el ref el, str tag) void removeClass (str | el ref | arr el, str className) removeChild()
Returns the first HTMLElement ancestor of the element with the Removes a class name from a given element or collection of replaceChild()
given tagName. elements.
scrollIntoView()
obj getAncestorByClassName (str | el ref el, str tag) void replaceClass (str | el ref | arr el, str oldClassName, str
setAttribute()
Returns the first HTMLElement ancestor of the element with the newClassName)
given className. Replace a class with another class for a given element or setInterval()
array getChildren (str | el ref el) collection of elements. setTimeout()
Returns the HTMLElement child nodes of the element. void setStyle (str | el ref | arr el, str property, str val)
array getElementsBy (fn method, str tag, str | el ref root) Wrapper for setting style properties of HTMLElements. Dom Node Properties:
Returns a array of HTMLElements that pass the test applied by void setX (str | el ref | arr el, int x)
supplied boolean method. For optimized performance, include Set the X position of the element(s) in page coordinates, attributes
a tag and/or root node when possible. regardless of how the element is positioned. childNodes
array getElementsByClassName (str className, str tag, str | el ref void setXY (str | el ref | arr el, arr pos, b noRetry) className
root) Set the position of the element(s) in page coordinates, disabled
Returns a array of HTMLElements with the given class. For regardless of how the element is positioned. firstChild
optimized performance, include a tag and/or root node when void setY (str | el ref | arr el, int y) id
possible. Set the Y position of the element(s) in page coordinates, innerHTML
obj getFirstChild (str | el ref el) regardless of how the element is positioned.
lastChild
Returns the first HTMLElement childNode of the element.
obj getLastChild (str | el ref el) Solutions nextSibling
Returns the last HTMLElement childNode of the element. nodeType
obj getNextSibling (str | el ref el) Get all elements to which the CSS class "header" has been applied: nodeName
Returns the next HTMLElement sibling of the element. headerEls = nodeValue
obj getPreviousSibling (str | el ref el) YAHOO.util.Dom.getElementsByClassName("header"); offsetHeight
Returns the previous HTMLElement sibling of the element.
Get all elements by attribute:
offsetWidth
obj getRegion (str | el ref | arr el) parentNode
Returns the region position of the given element. checkTitle = function(el) { previousSibling
str/array getStyle (str | el ref | arr el, str property) return (el.getAttribute("title")=="Click here.");}
myEls = YAHOO.util.getElementsBy(checkTitle, "a", "yui- tagName
Normalizes currentStyle and ComputedStyle.
main"); Note: These are not exhaustive lists.
int getX (str | el ref | arr el)
Gets the current X position of the element(s) based on page Set element's opacity using setStyle:
coordinates.
YAHOO.util.Dom.setStyle(myEl, "opacity", "0.5");
array getXY (str | el ref | arr el)
Gets the current position of the element(s) based on page
coordinates. Dependencies
int getY (str | el ref | arr el)
Gets current Y pos of the elem(s) based on page coordinates. The Dom Collection requires the YAHOO Global Object.
YUI Library: Drag & Drop 2009-2-6 v2.7
Simple Use Case: Making an Element Draggable Interesting Moments in Drag & Drop Drag & Drop Manager:
myDDobj = new YAHOO.util.DD("myDiv"); Moment Point Mode Intersect Mode Event (e) Properties
onMouseDown e e mousedown clickPixelThresh (i)
Makes the HTML element whose id attribute is "myDiv" draggable.
startDrag x, y x, y n/a clickTimeThresh (i)
onDrag e e mousemove useShim (b)
Constructor (YAHOO.util.DD, DDProxy, DDTarget) onDragEnter e, id e, DDArray mousemove mode either
YAHOO.util.DD(str | el ref target[, str group name, onDragOver e, id e, DDArray mousemove YAHOO.util.DragDropMgr.POI
NT or .INTERSECT
obj configuration]); onDragOut e, id e, DDArray mousemove
preventDefault (b)
onDragDrop e, id e, DDArray mouseup
Arguments: stopPropagation (b)
onInvalidDrop e e mouseup
(1) Element: ID or elem. ref. of the element to make draggable; useCache (b)
endDrag e e mouseup
deferral is supported if the element is not yet on the page.
onMouseUp e e mouseup
(2) Group Name: An optional string indicating the DD group; DD
These "moments" are exposed as events on your DD instances; they are methods of
Drag & Drop Manager:
objects only "interact with" other objects that share a group. YAHOO.util.DragDrop. The table above identifies the arguments passed to these methods Methods
(3) Configuration: An object containing name-value pairs, used to set in Point and Intersect modes.
oDD=instance of DragDrop object
any of the DD object’s properties.
Solutions getBestMatch(a [oDDs])
Properties & Methods of YAHOO.util.DragDrop getDDById(s id)
Add a drag handle to an existing DD object: getLocation(oDD)
Properties: myDDobj.setHandleElId('myDragHandle'); getRelated(oDD, b targets
Methods: removeInvalid
available (b) only)
addInvalidHandle HandleId(s id) Set the "padding" or "forgiveness zone" of a DD object:
dragOnly (b) Class (s cssClass) removeInvalidHandle isDragDrop(s id)
useShim (b) addInvalidHandleId (s Type (s tagName) myDDobj.setPadding(20, 30, 20, 30); //units are isHandle(s DDId, s
groups (ar) id) resetConstraints() pixels, top/rt/bt/left HandleId)
id (s) addInvalidHandle setDragElId(s id) Get the ‘best match’ from an onDragDrop event in Intersect Mode isLegalTarget(oDD, oDD
invalidHandle Type (s tagName) setHandleElId (s id) where the dragged element is over more than one target: target)
Classes (s[ ]) addToGroup (s setOuterHandleElId (s isLocked()
invalidHandleIds groupName) id) myDDobj.onDragDrop = function(e, DDArray) { lock()
(obj) clearTicks() setPadding(i top, i oDDBestMatch = refreshCache()
clearConstraints() right, i bottom, i YAHOO.util.DragDropMgr.getBestMatch(DDArray);} swapNode()
isTarget (b)
maintainOffset (b) getDragEl() left) Override an interesting moment method for a DD object instance: unlock()
padding (int[ ]) getEl() setXConstraint(i left, i
isLocked() right, i tick size) myDDobj = new YAHOO.util.DD("myDiv"); *Note: YAHOO.util.DragDropMgr
primaryButtonOnly myDDobj.startDrag = function(x,y) {
(b) lock() setYConstraint(i up, i is a singleton; changes made to
removeFromGroup(o down, i tick size) this.iStartX = x; this.iStartY = y; its properties (such as locking or
xTicks (int[ ]) } unlocking) affect Drag and Drop
dd, s group) unlock()
yTicks (int[ ]) globally throughout a page.
removeInvalid unreg() Change the look and feel of the proxy element at the start of a drag
HandleClass(s event using YAHOO.util.DDProxy:
cssClass) Dependencies
myDDobj.startDrag(x,y) {
YAHOO.util.Dom.addClass(this.getDragEl(), Drag & Drop
Properties & Methods of YAHOO.util.DD & .DDProxy "myCSSClass"); }
requires the YAHOO
Inherit from YAHOO.util.DragDrop and add the following: Lock Drag and Drop across the whole page: object, DOM, and
YAHOO.util.DragDropMgr.lock(); Event.
YAHOO.util.DD Properties: YAHOO.util.DDProxy
Switch to Intersect Mode:
scroll (b) Properties:
centerFrame (b) YAHOO.util.DragDropMgr.mode =
resizeFrame (b) YAHOO.util.DragDropMgr.INTERSECT;
YUI Library: Event Utility & Custom Event 2009-2-6 v2.7
Simple Use Case: Adding Event Listeners Simple Use Case: Custom Event Event Utility
Methods:
YAHOO.util.Event.addListener("myDiv", "click", myEvt = new YAHOO.util.CustomEvent("my event");
fnCallback); mySubscriber = function(type, args) { addListener(…) || on(…)
alert(args[0]); } //alerts the first argument getCharCode(e)
Adds the function fnCallback as a listener for the click event on an myEvt.subscribe(mySubscriber); getListeners(el [, type])
getPageX(e)
HTML element whose id attribute is myDiv. myEvt.fire("hello world");
getPageY(e)
Creates a new Custom Event instance and a subscriber function; the subscriber getRelatedTarget(e)
getTarget(e)
Invocation (addListener) alerts the event's first argument, "hello world", when the event is fired.
getTime(e)
getXY(e): returns array
YAHOO.util.Event.addListener(str | el ref | arr
Constructor (Custom Event) [pageX, pageY]
target[s], str event, fn callback[, obj onAvailable(s id || el ref, fn
associated object, b scope); YAHOO.util.CustomEvent(str event name[, obj scope object, callback, o obj, b scope)
b silent, int signature ]); onBlur(el, fn callback, o obj,
Arguments: b scope) adds a DOM blur
(1) Element or elements: You may pass a single element or group of Arguments: event listener to an el
(1) Event name: A string identifying the event. onContentReady(s id || el
elements in an array; references may be id strings or direct element ref, fn cllbck, o obj, b scp)
(2) Scope object: The default scope in which subscribers will run; can be
references. onDOMReady(s id || el ref, fn
overridden in subscribe method.
(2) Event: A string indicating the event ('click', 'keypress', etc.). (3) Silent: If true, hides event's activity from Logger when in debug mode.
callback, o obj, b scope)
(3) Callback: The function to be called when the event fires. onFocus(el, fn callback, o
(4) Argument signature: YAHOO.util.CustomEvent.LIST by default — all obj, b scope) adds a DOM
(4) Associated object: Object to which your callback will have arguments passed to handler in a single array. .FLAT can be specified to focus event listener to el
access; often the callback's parent object. pass only the first argument. preventDefault(e)
(5) Scope: Boolean — if true, the callback runs in the scope of the purgeElement(el [, recurse,
type])
associated object. Subscribing to a Custom Event removeListener(…)
stopEvent(e): same as
Event Utility Solutions myEvt.subscribe(fn callback[, obj associated object, b
scope]);
preventDefault plus
stopPropagation
stopPropagation(e)
Using onAvailable: Arguments for subscribe:
fnCallback = function() { //will fire when element (1) Callback: The function to be called when the event fires. DOM Event Object
(2) Associated object: Object to which your callback will have access as an Props & Methods:
becomes available}
argument; often the callback's parent object.
YAHOO.util.Event.onAvailable('myDiv', fnCallback); (3) Scope: Boolean — if true, the callback runs in the scope of the associated altKey (b)
object. bubbles (b)
Using Event's convenience methods: cancelable (b)
fnCallback = function(e, obj) { Arguments received by your callback function: *charcode (i)
myTarget = YAHOO.util.Event.getTarget(e, 1); When using the default argument signature (YAHOO.util.CustomEvent.LIST; clientX (i)
see Constructor section above), your callback gets three arguments: clientY (i)
//2nd argument tells Event to resolve text nodes ctrlKey (b)
} (1) Type: The type of Custom Event, a string. currentTarget (el)
YAHOO.util.Event.addListener('myDiv', 'mouseover', (2) Arguments: All arguments passed in during fire, as an array. eventPhase (i)
fnCallback, obj); (3) Associated object: The associated object passed in during subscribe, if isChar (b)
keyCode (i)
present.
Prevent the event's default behavior from proceeding: metaKey (i)
myEvt.fire(arg1, arg2); *pageX (i)
YAHOO.util.Event.preventDefault(e); var myHandler = function(sType, aArgs, oObj) {/*aArgs=[arg1, arg2]*/}; *pageY (i)
myEvt.subscribe(myHandler, oObj); *preventDefault()
Remove listener: *relatedTarget (el)
When using the optional argument signature (YAHOO.util.CustomEvent.FLAT;
screenX (i)
YAHOO.util.Event.removeListener('myDiv', see Constructor section above), your callback gets two arguments:
screenY (i)
'mouseover', fnCallback); (1) Argument: The first argument passed when the event is fired. shiftKey (b)
(2) Associated object: Passed in during subscribe, if present. *stopPropagation()
Dependencies myEvt.fire(arg1); *target (el)
var myHandler = function(arg, oObj) {/*arg=arg1*/}; *timestamp (long)
Event Utility requires the YAHOO Global Object. myEvt.subscribe(myHandler, oObj); type (s)
[ *use Event Utility method ]
YUI Library: Get Utility 2009-2-6 v2.7
Simple Use Case: Get an External Script Configuration Options* YAHOO.util.Get Methods
Field Type Description css(string | arr URLs[, obj config
With the Get Utility on the page, you can bring in an external onSuccess fn Callback method invoked when the requested file(s) have
options]) see usage at right
script file in two steps: loaded successfully.
script(string | arr URLs[, obj config
options]) see usage at right
onFailure fn Callback method invoked when an error is detected or abort
1. Define the logic you want to execute when the script is called.
abort(string | obj tId) takes either the
transaction id or transaction object
successfully loads; onTimeout Fn Callback method invoked when a resource doesn’t load within generated by script or css; aborts
2. Get the script. the timeframe specified by the timeout config. transaction if possible; fires onFailure
timeout Int The number of millisecond to wait for a resource to load. handler
var successHandler = function(oData) { win obj The window into which the loaded resource(s) will be inserted.
//code to execute when all requested scripts have been
//loaded; this code can make use of the contents of those
scope obj The execution scope in which the callbacks will run. YAHOO.util.Get Global
data any Data to pass as an argument to all callbacks.
//scripts, whether it's functional code or JSON data.
autopurge bool If true, script nodes will automatically be removed every 20
Configuration Properties
} transactions (configurable via YAHOO.util.Get.POLL_FREQ int
var aURLs = [ YAHOO.util.Get.PURGE_THRESH property. Default: true when polling is necessary to check on the
for script nodes, false for CSS nodes. status of a loading file (eg, where the load
"/url1.js", "/url2.js", "/url3.js" //and so on event is unreliable), this controls the
varName arr (of Safari 2.x does not reliably report the load-complete status of polling interval in milliseconds
]; strings) script nodes; use this property to provide Get with a globally YAHOO.util.Get.PURGE_THRESH int
YAHOO.util.Get.script(aURLs, { accessible property that will be available when the script has controls the number of added script or
loaded. This array is parallel to the urls array passed in as the link nodes that will accumulate prior to
onSuccess: successHandler first argument to script(). being automatically purged
}); insertBefore str|el Element reference or id of a node that should be used as the
insertion point for new nodes. This is useful for making sure
CSS rules are parsed in the correct order (place your style Dependencies
Usage: YAHOO.util.Get.script() overrides in a single style block and insertBefore this node).
charset str The charset attribute for new node(s). Default: utf-8 The Get Utility requires only
YAHOO.util.Get.script(str or arr url[s][, obj the YAHOO Global Object.
options]) Callback Arguments
Arguments: Fields available in the object passed to your onSuccess or onFailure callback.
* Use configuration options by
(1) URL[s]: A string or array of strings containing the URL[s] to Field Type Description
passing an optional object containing
tId str The unique identifier for this transaction; this string is available as the
be inserted in the document via script nodes. tId member of the object returned to you upon calling the script or
config options to
YAHOO.util.Get.script or
(2) options: An object containing any configuration options you’d css method. YAHOO.util.Get.css as the
like to specify for this transaction. See the Configuration data any The data field you passed to your configuration object when the second argument:
YAHOO.util.Get.script(“http
Options table for the full list of options. script or css method was called. Default: null. ://json.or/json.js”,
win obj The window into which the loaded resource(s) were inserted. {onSuccess: function(o)
Returns: nodes array An array containing references to node(s) created in processing the {YAHOO.log(“success!”);}});
(1) Transaction Object: Object containing single field, stru tId, a transaction. These will be script nodes for JavaScript and link nodes
for CSS.
unique string identifying this transaction.
purge Fn Calling the returned purge() method will immediately remove the
Note: Scripts downloaded will be executed immediately; only use this method to procure created nodes.
JavaScript whose source is trustworthy beyond doubt.

Solutions
Usage: YAHOO.util.Get.css()
Set up a transaction making use of configuration options; then make use
YAHOO.util.Get.css(str or arr url[s][, obj of the data passed to the callback handler:
options]) var successHandler = function(o) {
//o contains all of the fields described in the callback args table
Arguments: o.purge(); //removes the script node immediately after executing;
(1) URL[s]: A string or array of strings containing the URL[s] to YAHOO.log(o.data); //the data passed in configobject
be inserted in the document via link nodes. }
(2) options: An object containing any configuration options you’d var objTransaction = YAHOO.util.Get.script("http://json.org/json.js",
like to specify for this transaction. See the Configuration { onSuccess: successHandler,
scope: this, //successHandler will run in the scope of “this”
Options table for the full list of options. data: {field1: value1, field2: value2}} //you can pass data in
Note: Returns the same Transaction Object as script(); see above. //any format here
);
YUI Library: ImageCropper Control [beta] 2009-2-6 v2.7
Simple Use Case: YAHOO.widget.ImageCropper ImageCropper Events YAHOO.widget.ImageCropper:
See online docs for complete list of Resize events. Methods
Markup: Event Fires...
<img src="yui.jpg" id="crop1"> getActiveHandleEl() Get the HTML
dragEvent Fires when the DragDrop dragEvent is fired. reference for the currently active resize
Script: startResizeEvent Fires when a resize action is started. handle.
crop = new YAHOO.widget.ImageCropper('crop1'); resizeEvent Fires on event element resize getCropCoords() Get the coordinates
needed to crop the image
Using the above code will get you a rich control that looks moveEvent Fires on every element move. Inside these methods:
_handleKeyPress, _handleDragEvent,
getCropperById() Get an
something like this: ImageCropper object by the HTML id of
_handleResizeEvent the image associated with the
ImageCropper object.
All ImageCropper events are Custom Events (see Element docs); subscribe to these events
using their subscribe method: crop.on(‘resize',fnMyHandler);. getEl() Get the HTML reference for the
image element.
getMaskEl() Get the HTML reference for
Key ImageCropper Configuration Options the mask element.
See online docs for complete list of ImageCropper configuration options. getResizeEl() Get the HTML reference
for the resize element.
Option Default Description
initHeight 1/4 of the Set the initlal height of the crop area. getResizeMaskEl() Get the HTML
reference for the resizable object's mask
image height element.
initWidth 1/4 of image Set the initla width of the crop area. getResizeObject() Get the Resize
width Utility object.
initialXY [10,10] Array of the XY position that we need to set the getWrapEl() Get the HTML reference for
crop element to when we build it. the wrap element.
keyTick 1 The pixel tick for the arrow keys. destroy() Destroys the ImageCropper
object and all of its elements & listeners.
ratio false Constrain the resize to a ratio of the current
size.
status True Show the Resize Utility status.
Most of ImageCropper’s options can be set in the constructor's second argument (eg,
{ratio: true}) or at runtime via set (eg, crop.set("ratio", true);).

Constructor: YAHOO.widget.ImageCropper Getting the crop area


YAHOO.widget.ImageCropper(str | el ref //set up a new cropper
container[, obj config]) var cropImg = new YAHOO.widget.ImageCropper('img1');
//get the crop area
Arguments:
var cropArea = cropImg.getCropCoords();
(1) Element: The element to make croppable.
(2) Configuration object: When instantiating the ImageCropper // cropArea now looks like this:
Control, you can pass all configurations in as an object
argument or configure the instance after instantiation. See {
Configuration Options section for common configuration object top: 70,
members. left: 122,
height: 86,
Dependencies width: 172,
image: 'yui.jpg'
ImageCropper requires the Yahoo Global Object, Dom, Event, Element, }
DragDrop, and Resize.
YUI Library: ImageLoader Utility 2009-2-6 v2.7
Simple Use Case: ImageLoader Group Object ImageLoader Objects: Members YAHOO.util.ImageLoader.
See online docs for complete details on members. group Methods:
Create a YAHOO.util.ImageLoader.group object with a
YAHOO.util.ImageLoader.group addTrigger(obj domObject or str
trigger and time limit. Then register images with the group: domElementId, str eventAction)
Member Type Description adds a trigger event
//group with ‘someDivId’ click trigger & 2 sec limit: addCustomTrigger(obj
var myGroup = new YAHOO.util.ImageLoader.group('someDi timeoutLen number Length of time limit, in seconds. Also the
YAHOO.util.CustomEvent object)
vId', 'click', 2); third argument in the constructor. adds a custom event trigger
myGroup.registerBgImage('imgDivId', 'http://some.image foldConditional boolean Flag to check if images are above the fold. registerBgImage(str imgElId, str url)
/url'); adds a background-type image to the
className string CSS class name that will identify images group returns
YAHOO.util.ImageLoader.imgObj
This will cause imgDivId's background image to load either belonging to the group.
registerSrcImage(str imgElId, str url,
when someDivId is clicked or two seconds after page load, name string Optional. Only used to identify the group in [int width, int height]) adds a source-
whichever comes first. Logger Control logging statements. type image to the group; optional width
and height resize the image to those
addTrigger method Adds a trigger to the group. constraints returns
Constructor: ImageLoader Group Object addCustomTrigger method Adds a custom event trigger to the group.
YAHOO.util.ImageLoader.imgObj
registerPngBgImage(str imgElId, str
YAHOO.util.ImageLoader.group([obj triggerElement, str url, [obj ailProps]) adds a png-
registerBgImage method Registers a background image with the background-type image to the group;
triggerAction, int timeLimit]) group. optional properties to set
AlphaImageLoader properties returns
Arguments: registerSrcImage method Registers a src image with the group. YAHOO.util.ImageLoader.imgObj
(1) triggerElement: The object of the trigger event. Can be a registerPngBgImage method Registers an alpha-channel-type png
DOM id or object. background image with the group. Dependencies
(2) triggerAction: The action of the trigger event. YAHOO.util.ImageLoader.imgObj
triggerElement and triggerAction are optional (can be The YUI ImageLoader
Member Type Description Utility requires the Yahoo
null). But if one is supplied, the other must be as well.
(3) timeLimit: Maximum time to wait for the trigger event to be setVisible boolean Whether the style.visibility should be set to Global Object, Dom
fired. “visible” after the image is fetched. Collection, and Event Utility.
width number Size to set as width of image after image is
ImageLoader Image Registration fetched. Only applies to source-type
images. Third argument in group’s
Source images (e.g., an <img> element): registerSrcImage method.
myGroup.registerSrcImage(‘imgImgId’,
‘http://some.image/url’); height number Size to set as height of image after image is
fetched. Only applies to source-type
Background images (e.g., a <div> element with a background image): images. Fourth argument in group’s
myGroup.registerBgImage(‘imgDivId’, registerSrcImage method.
‘http://some.image/url’);
PNG background images (e.g., a <div> element with a PNG bg image): Solution: Image Loading with Class Names
myGroup.registerPngBgImage(‘imgDivId’,
‘http://some.png_image/url’); Set up the CSS, HTML, and JavaScript for delayed image loading:
/* set an overriding background:none */
.yui-imgload-circle { background:none !important; }
Solution: Simple Image Loading <!-- this div will get the trigger event -->
<div id='circle'>
Set up the HTML and JavaScript for delayed image loading: <!-- set the src to some transparent image, the background-
image to the true image, and the class to match the CSS -->
<div id='square'> <img id='circleImg' src=‘http://some.transparent/image’
<img id='squareImg' /><!-- note no “src” attribute --> style=‘background-image:url(“http://some.image/url”);’
</div> class=‘yui-imgload-circle’ height=‘20’ width=‘20’ />
// in script, create group and register image </div>
var sqGrp = new YAHOO.util.ImageLoader.group(‘square’, // create group and identify class name
var circleGroup = new YAHOO.util.ImageLoader.group(‘circle’,
‘mouseover’, 3);
‘mouseover’, 3);
sqGrp.registerSrcImage(‘squareImg’, circleGroup.className = ‘yui-imgload-circle’;
‘http://some.image/url’);
YUI Library: JSON Utility 2009-2-6 v2.7
Simple Use Case: Parse a JSON string Using the JSON Format YAHOO.lang.JSON Methods
parse(str JSON[,fn reviver]) see usage
One of the core use cases for the JSON Utility is to take string JSON data is characterized as a collection of objects, arrays, booleans, at left
data formatted in JavaScript Object Notation and to validate the strings, numbers, and null. The notation follows these guidelines: stringify(obj object[, arr whitelist | fn
replacer[, n depth]]) see usage at left
string as genuine JSON before evaluating it and processing it in isValid(str JSON) see online docs
script. YAHOO.lang.JSON.parse() provides this functionality: 1. Objects begin and end with curly braces ({}).
2. Object members consist of a string key and an associated value
var jsonString = ‘{"productId":1234, Dependencies
"price":24.5, "inStock":true, "bananas":null}’; separated by a colon ( "key" : VALUE ).
// Parsing JSON strings can throw a SyntaxError 3. Objects may contain any number of members, separated by The JSON Utility requires
// exception, so we wrap the call commas ({ "key1" : VALUE1, "key2" : VALUE2 }). only the YAHOO Global
// in a try catch block 4. Arrays begin and end with square braces and contain any number Object.
try { of values, separated by commas ([ VALUE1, VALUE2 ]).
var prod=YAHOO.lang.JSON.parse(jsonString); 5. Values can be a string, a number, an object, an array, or the literals
}
true, false, and null.
catch (e) {
alert("Invalid product data"); 6. Strings are surrounded by double quotes and can contain Unicode
} characters and common backslash escapes ("new\nline").
// We can now interact with the data
if (prod.price < 25) { JSON.org has helpful format diagrams and specific information on
prod.price += 10; // Price increase! allowable string characters.
}
Solutions: Using the reviver argument
Usage: YAHOO.lang.JSON.parse()
You can filter out and/or reformat specific pieces of data while applying
YAHOO.lang.JSON(str JSON[, fn reviver]) the parse method by passing in a second (optional) argument,
Arguments: reviver. Reviver is a function that is passed the key and value of the
(1) JSON: A string containing JSON-formatted data that you item it is filtering; based on the key and value, the filter can return a
wish to validate and parse. formatted value for the item or return undefined to omit the key
(2) reviver: A function that will be executed on each member of altogether.
the JSON object; see the Solutions box for more. var currencySymbol = "$"
function myFilter(key,val) {
Returns: // format price as a string
JavaScript representation: The returned value of the evaluated if (key == "price") {
JSON string (if no exception was thrown in its evaluation). var f_price = currencySymbol + (val % 1 ? val + "0" :
val + ".00");
return f_price.substr(0,f_price.indexOf('.') + 3);
Usage: YAHOO.lang.JSON.stringify() }
YAHOO.lang.JSON.stringify(obj object[, arr // omit keys by returning undefined
whitelist | fn replacer[, n depth]]) if (key == "bananas") {
return undefined;
Arguments: }
(1) object: The JavaScript object you want to stringify. }
(2) whitelist: An optional array of acceptable keys to include. var formattedProd = YAHOO.lang.JSON.parse(jsonString,
(2*) replacer: A function to offer a replacement value for myFilter);
serializing. Executed on each member of the input object. // key "bananas" is not present in the formattedProd object
(3) depth: An optional number specifying the depth limit to if (YAHOO.lang.isUndefined(formattedProd.bananas)) {
which stringify should recurse in the object structure (there is alert("We have no bananas today");
a practical minimum of 1). }
Returns: // and the price is the formatted string "$24.50"
alert("Your price: " + formattedProd.price)
JSON string: A JSON string representing the object.
YUI Library: Layout Manager 2009-2-6 v2.7
Simple Use Case: Creating a Layout Layout Configuration Options YAHOO.widget.Layout
Field Type Description
Methods
Layouts can be created targeting the full browser viewport:
height integer Height of the Layout in pixels. addUnit(o cfg) there must not be a
var layoutFull = new YAHOO.widget.Layout({/* Config LayoutUnit at the new unit’s position
minHeight integer Minimum height of the Layout in pixels. getLayoutById(s id) static method,
here */});
minWidth integer Minimum width of the Layout in pixels. returns Layout whose parent is element id
layoutFull.render();
parent Layout If this Layout is a child of another Layout, this attribute getSizes() returns object containing sizes
Layouts can also target a specific page element: object sets the relationship and binds the Layouts’ resize of all child Layout Units
getUnitById(s id) returns LayoutUnit
//Element Based Layout events together. whose parent is element id
var layoutEl = new YAHOO.widget.Layout('demo', { /* width integer Width of the Layout in pixels. getUnitByPosition(s pos) returns
Config here */}); Configuration options should be set in the second argument of the constructor: Layout Unit at specified position
var pv = new YAHOO.widget.Layout(“myEl”, {height: 400});. removeUnit(o unit) removes the unit;
layoutEl.render(); Layout resizes automatically
Layouts consist of up to five Layout Units (top, right, bottom, left and Key Interesting Moments in Layout
center; center is required, fluid, and cannot be resized). YAHOO.widget.LayoutUnit
var layoutFull = new YAHOO.widget.Layout({
Event Description/Fields: Properties
render Event fires when the rendering of the Layout is complete.
units: [{position: 'top'}, {position: 'center'}] body, header, and footer HTML
beforeResize Fires at the beginning of the resize process; return false to elements for specified sections
});
layoutFull.render(); prevent resize.
resize Fires after the resize process completes. YAHOO.widget.LayoutUnit
See Layout Units section for more on configuring a Layout Unit. Subscribe: layout.on(“render”, function(o){});.
Methods
Constructor: YAHOO.widget.Layout Key Interesting Moments in LayoutUnit close() collapses and removes the unit
collapse() collapses the unit, if not already
YAHOO.widget.Layout([str | obj container,] obj
Event Description/Fields: collapsed
close Fires when the unit is closed. destroy() removes the unit and cleans up
configuration) references and listeners
collapse Fires when the unit is collapsed. expand() expands the unit, if not already
Arguments: contentChange Fires when header/body/footer content is changed via API. expanded
(1) Container (optional): A reference to a DOM element (by ID or direct expand Fires when the unit is expanded. getLayoutUnitById(s id) static method
reference) that will contain the Layout; if this argument is omitted, the beforeResize Fires at the beginning of the resize process; return false to returns the unit that is associate with a
Layout will take up the full browser viewport. given HTML id
prevent resize. getUnitByPosition(s pos) returns
(2) Configuration: An optional object containing your desired resize Fires after the resize process completes. Layout Unit at specified position
configuration options, including information about your Layout Units. getSizes() returns object containing size
Subscribe: layoutUnit.on(“close”, function(o){});.
See Layout Units and Configuration Options sections for details. information for this unit

Solutions: Embedding a Layout inside another Layout


Layout Units: Key Configuration Attributes Dependencies
var layout = new YAHOO.widget.Layout({
animate Use animation on resize Is this unit resizeable?
expand/ collapse?
units: [ Layout Manager/Unit
collapse Adds collapse icon scroll Is units body content
{ position: 'top', height: 300, body: 'Top #1'}, requires: Yahoo, Dom,
scrollable? { position: 'center', body: '' } //empty body for next layout Event and Element.
duration Duration in ms of width Width of unit in px ] Animation, DragDrop,
animation transition }); Resize and Selector are
easing Animation easing header/ Contents of the header, layout.on('render', function() { optional.
effect to use (see body/ body and footer sections
var c = layout.getUnitByPosition('center');
anim docs) footer of the unit //Apply the new layout to the body element of the first layout
gutter Gutter surrounding Layout Units can be instantiated or var layout2 = new YAHOO.widget.Layout(c.body, {
unit (in px; supports created and configured as part of the parent: layout,
“t r b l” or “tb rl” css- Layout constructor:
units: [
style syntax) var layoutFull = new { position: 'left', width: 200, body: 'Left #2'},
height Height of this unit in YAHOO.widget.Layout({
px units: [ { position: 'center', body: 'Center #2' }
maxHeight/Width, Max/min dimensions {position: 'center', ]
gutter: "5 7 0 5”, });
minHeight/Width of unit in px. scroll: true,
position Position of this unit minHeight: 225 layout2.render();
in the Layout (top, }] });
right, bottom, left or }); layout.render();
layoutFull.render();
center)
YUI Library: Logger 2009-2-6 v2.7
Simple Use Case (LogReader) Simple Use Case (Logger) YAHOO.widget.Logger
Static Properties:
<div id="myLogger"></div> YAHOO.log("My log message", "error", "mysource");
loggerEnabled (b)
<script>
Logs a message to the default console and to console.log(), if maxStackEntries (int)
var myLogReader = new
enabled; the source is "mysource" and the category is "error". Custom
YAHOO.widget.LogReader("myLogger"); YAHOO.widget.Logger
categories and sources can be added on the fly.
</script> Static Methods:
Instantiates a new LogReader object, myLogReader, which is bound to
Constructor (LogWriter) log(sMsg, sCategory,
a div whose id attribute is 'myLogger'. The result will be a visual sSource)
LogReader display. Creates a separate, named bucket for your log messages: disableBrowserConsole()
enableBrowserConsole()
To create a LogReader that floats outside YAHOO.widget.LogWriter(str sSource); getStack()
the page context, omit the reference to a getStartTime()
Arguments:
context div. Your LogReader will then be reset()
(1) Source (string): The source of log messages. The first word of the
appended to the page and positioned
absolutely. If the YUI Drag & Drop Library
string will be used to create a LogReader filter checkbox. The entire YAHOO.widget.Logger
is included on the page, it will be
string will be prepended to log messages so they can be easily Custom Events:
tracked by their source.
draggable. categoryCreateEvent
sourceCreateEvent
Solutions newLogEvent
logResetEvent
Constructor (LogReader) Log a message using a pre-styled logging category:
LogReader Properties:
YAHOO.widget.LogReader([str html id | obj element YAHOO.log("My log message.", "warn");
verboseOutput (b)
reference, obj configuration object]); Create a new logging category on the fly: newestOnTop (b)
Arguments: YAHOO.log("My log message.", "myCategory"); thresholdMax (int)
(1) HTML element (string or object): An optional reference to an thresholdMin (int)
HTML id string or element object binds the LogReader to an existing Style a custom logging category in CSS: outputBuffer (int)
page element. .yui-log .myCategory {background-color:#dedede;} LogReader Methods:
(2) Configuration object (object): An optional object literal defines
Log a message, creating a new "source" on the fly: hide()/show()
LogReader settings. All properties of a LogReader instance can be pause()/resume()
set via the constructor by using this object. YAHOO.log("My log message.", "warn", "newSource");
collapse()/expand()
In script, hide and show the logging console: clearConsole()
Logging via console.log() myLogReader.hide();
hideCategory()/
showCategory()
A growing number of browsers and extensions support the JavaScript myLogReader.show(); hideSource()/
method console.log(). The excellent FireBug extension to FireFox In script, pause and resume output to the console: showSource()
supports this method, as does the JavaScript console in Apple's Safari myLogReader.pause(); LogWriter Methods:
browser. Enable this feature using Logger's myLogReader.resume(); log(sMsg, sCategory,
enableBrowserConsole() method.
Instantiate your own LogWriter to write log messages categorized sSource)
by their source:
Dependencies Categories
MyClass.prototype.myLogWriter = new (Pass in other
Logger requires the YAHOO object, Dom, and Event; Drag & Drop is YAHOO.widget.LogWriter("MyClass of MyApp"); info
categories to
optional. Use in combination with –debug versions of YUI files for var myInstance = new MyClass(); warn
to add
built-in logging from components. myInstance.myLogWriter.log("This log message can now error log()
to this list.)
be filtered by its source, MyClass."); //"MyClass time
of MyApp", the full name of the source, will be window
prepended to the actual log message
YUI Library: Menu 2009-2-6 v2.7
Simple Use Case: YAHOO.widget.Menu Key Interesting Moments in Menu YAHOO.widget.Menu:
See online docs for a complete list of Menu’s Custom Events. Properties
Markup (optional, using standard module format): itemAdded show parent
<div id="mymenu">
itemRemoved hide element
<div class="bd"> id
<ul> render beforeShow
<li><a href=” … ”>item one</a></li> beforeRender beforeHide
All Menu events are YUI Custom Events (see Event Utility docs); subscribe to these events YAHOO.widget.Menu:
<li><a href=” … ”>item two</a></li>
using their subscribe method: oMenu.subscribe(“show”, fnMyHandler);.
</ul> Methods
</div>
</div>
Key Menu Configuration Options addItem(o || s [,i])
See online docs for complete list of Menu options. addItems(o || s [,i])
Script: Option (type) Default Description getItem(i [,i])
var oMenu = new YAHOO.widget.Menu("mymenu"); constrain true Forces a Menu to remain inside the confines getItems()
getItemGroups()
oMenu.render(); toviewport (b) of the viewport.
getSubmenus()
oMenu.show(); itemData (a) null Array of MenuItems to be added to Menu.
getRoot() returns root Menu
lazyLoad (b) false Boolean value specifies whether Menu instance
Creates, renders and shows a menu using existing markup. should defer initialization and rendering of insertItem(o || s [,i] [,i])
submenus until needed. removeItem(o || i [,i])
Constructor: YAHOO.widget.Menu position (s) "dynamic" Static: in the flow of the document, visible by setItemGroupTitle(s [,i])
(“static” for default. Dynamic: hidden by default, outside show()
YAHOO.widget.Menu(str elId[, obj config]); MenuBar) of page flow. hide()
submenuhidedelay 250 Delay (in ms) for hiding a submenu as a user clearContent()
Arguments: (n) mouses out of parent MenuItem while render([el])
(1) Element ID: HTML ID of the element being used to create the mousing toward the submenu. destroy()
Menu. If this element doesn't exist, it will be created and showdelay (n)/ 250 (show), Built-in delay when showing or hiding the
appended to the document body. hidedelay (n) 0 (hide) Menu, in miliseconds. YAHOO.widget.
(2) Configuration Object: JS object defining configuration trigger (s || o || a) Null The id(s) or node reference(s) for the
properties for the Menu instance. See Configuration section for element(s) whose contextmenu event MenuItem: Properties
full list. triggers the context menu's display. element
maxheight (n) 0 The maximum height (in pixels) for a menu parent
before the contents of the body are scrolled. id
Three Types of Menus shadow b Renders a Menu with a shadow. groupIndex
keepopen b Keeps the Menu open when clicked. index
Menu options can be set in the constructor's second argument (eg, {visible: true}) or at value
runtime via setProperty (eg, oMenu.cfg.setProperty("visible", false);).

YAHOO.widget.
Key MenuItem Configuration Options
See online docs for complete list of MenuItem options. MenuItem: Methods
Option (type) Default Description focus()
checked (b) false Renders the item with a checkmark. blur()
disabled (b) false If set to true the MenuItem will be
dimmed and will not respond to user input
or fire events. Dependencies
selected (b) false If set to true the MenuItem will be
highlighted. Menu requires the
submenu (o) null Appends a menu to the MenuItem. Container Core
target (s) null Value for the "target" attribute of the package, the YAHOO
item’s anchor element. Object, Event, and
text (s) null Text label for the item.
Dom.
url (s) "#" URL for the anchor's "href" attr.
MenuItem options can be set in the constructor's second argument (eg, {disabled: true})
or at runtime via setProperty (eg, oMenuItem.cfg.setProperty("disabled", true);).
YUI Library: Panel 2009-2-6 v2.7
Simple Use Case: YAHOO.widget.Panel Key Interesting Moments in Panel YAHOO.widget.Panel:
See online docs for a complete list of Panel’s Custom Events. Properties
Markup (optional, using standard module format): Event Arguments
<div id="myPanel"> body (el)
<div class="hd">Header content.</div> beforeRenderEvent None. element (el) containing
<div class="bd">Body content.</div> renderEvent None. header, body & footer

beforeShowEvent None. footer (el)


<div class="ft">Footer content.</div> header (el)
</div> showEvent None.
beforeHideEvent None. id (s) of the element
Script:
hideEvent None.
var oPanel = new YAHOO.widget.Panel("myPanel"); YAHOO.widget.Panel:
beforeMoveEvent X, Y to which the Panel will be moved.
oPanel.render(); Methods
oPanel.show(); moveEvent X, Y to which the Panel was moved.
hideMaskEvent None. appendToBody(el
Creates, renders and shows a panel using existing markup and all showMaskEvent None. element)
default Panel settings. changeContentEvent None. appendToFooter(el
changeBodyEvent String or element representing new body element)
Constructor: YAHOO.widget.Panel content (Note: there are corresponding Header and appendToHeader(el
Footer change events, too). element)
YAHOO.widget.Panel(str elId[, obj config]); All Panel events are YUI Custom Events (see Event Utility docs); subscribe to these events hide()
using their subscribe method: myPanel.hideEvent.subscribe(fnMyHandler);. render([el element])
Arguments:
Argument required for
(1) Element ID: HTML ID of the element being used to create the
Panel. If this element doesn't exist, it will be created.
Key Panel Configuration Options Panels not built from existing
markup. Panel will not be in
See online docs for complete list of Panel options; see Solutions (bottom left) for how to set your options. the DOM or visible until
(2) Configuration Object: JS object defining configuration properties render is called
for the panel. See Configuration section for full list. Option (type) Default Description
close (b) null Display close icon. setBody(str or el
draggable (b) null Make the Panel draggable. content)
Solutions modal (b) null Enforce Panel modality with a modal mask setFooter(str or el
visible (b) true Sets the “display” style property to “block” content)
There are three ways to configure options on your Panel: (true) or “none” (false). setHeader(str or el
// 1. In the constructor, via an object literal: x, y, and xy (int, null These properties can be used to set the content)
var myPanel = new YAHOO.widget.Panel("myPanel", { int, arr) Panel’s “top” and/or “left” styles. show()
visible:false }); context (arr) null Anchors Panel to a context element; format: bringToTop()
[el contextEl, s panelCorner, s
// 2. Via "queueProperty", prior to rendering: focusFirst()
contextCorner] with corners defined as
myPanel.cfg.queueProperty("visible",false); focusLast()
“tr” for “top right” and so on.
// 3. Via "setProperty" after rendering:
fixedcenter (b) false Automatically center Panel in viewport?
myPanel.cfg.setProperty("visible",false);!
width (s) null Sets “width” style property.
Dependencies
Align the top left corner of your Panel with the bottom right corner height (s) null Sets “height” style property.
of an element whose HTML ID is "contextEl": zindex (int) null Sets “z-index” style property. Panel requires the full
constrainto false When true, prevents the Panel from being Container package,
myPanel.cfg.setProperty(“context”, [“contextEl”, viewport (b) dragged out of the viewport.
“tl”, “br”]); the YAHOO object,
underlay (s) “shadow” Type of underlay: “shadow”, “none”, or
Event, and Dom.
Subscribe to a Panel Custom Event, listening for changes to the “matte”.
effect (obj) null Object defining effect (FADE or SLIDE) to Animation, and Drag
Panel’s postion, alerting its new position after move: and Drop are
use in showing and hiding Panel: {effect:
alertMove = function(type, args) { YAHOO.widget. optional. Note: By
alert(args[0] + “, “ + args[1]); ContainerEffect.FADE, duration:1} default, Panels
} autofillheight (s) “body” The element which will fill out the container enable Drag and
myPanel.subscribe(“move”, alertMove); height when the “height” config property is Drop if included on
set: “body”, “footer”, “header” or null the page
YUI Library: Profiler 2009-2-6 v2.7
Simple Use Case: Profiler Object Function Report Object YAHOO.tool.Profiler
When YAHOO.tool.getFunctionReport() is called, an object with the following properties is returned. Registration Methods
To use Profiler, register your target functions with the Member Type Description registerConstructor(string name,
YAHOO.tool.Profiler object and then call the function as avg float The average amount of time (in milliseconds) that the func owner) registers a constructor for
you would normally: function took to execute. profiling
registerFunction(string name, func
var object = { calls int The number of times that the function was called. owner) registers a function for profiling
method: function(){ min float The average amount of time (in milliseconds) that the registerObject(string name, obj
} function took to execute. object, bool recurse) registers all
max float The average amount of time (in milliseconds) that the methods on an object for profiling
}; unregisterConstructor(string name)
function took to execute. unregisters a constructor that was
//register the function points float[] An array containing the actual execution times (in previously registered
YAHOO.tool.Profiler.registerFunction( milliseconds) of the function. unregisterFunction(string name)
unregisters a function that was previously
"object.method", object); registered
Usage: YAHOO.registerObject() unregisterObject(string name)
//call the function unregisters all methods on an object that
object.method(); YAHOO.tool.Profiler.registerObject(str name[, obj were previously registered
object[, bool recurse]])
Usage: YAHOO.registerFunction() YAHOO.tool.Profiler Reporting
Use registerObject to register all of the methods on an object (use
Methods
YAHOO.tool.Profiler.registerFunction(str name[, registerFunction to register a single method).
getAverage(str name) returns the
obj owner]) Arguments: average amount of time (in ms) the
function with the given name took to
Arguments: (1) name: A string containing the fully-qualified name of the object (e.g. execute
(1) name: A string containing the fully-qualified name of the myobject or YAHOO.util.Dom). getCallCount(str name) returns the
number of times that the given function
function (e.g. myobject.mymethod). Profiler knows to (2) object: The object represented by the name. This argument may be was called
extract everything after the last dot as the short function safely omitted if the name exists in the global scope. getMax(str name) returns the maximum
name. (3) recurse: Indicates if object properties should also be should also amount of time (in ms) the function with
the given name took to execute
(2) owner: The object that owns the function (e.g. myobject for have their methods registered. getMin(str name) returns the minimum
amount of time (in ms) the function with
myobject.mymethod). This argument may be safely omitted the given name took to execute
if the name exists in the global scope. Solutions getFunctionReport(str name) returns
an object containing all information about
Note: Only functions that exist on objects can be profiled. Global functions are considered a given function including call count and
properties of the window object, so they can be registered but functions declared inside of other The basic use case of Profiler is to register one or more functions, run average, min, and max calls times
functions cannot be registered unless attached to an object. the application as you normally would, retrieve information about specific getFullReport(func filter) returns an
functions (or a complete report), and then unregister the functions (a object containing profiling information for
all registered functions
Usage: YAHOO.registerConstructor() necessary step to clean up memory if you wish to persist the browser
session).
YAHOO.tool.Profiler.registerConstructor(str Dependencies
//register the function
name[, obj owner])
YAHOO.tool.Profiler.registerFunction( Profiler requires only the
Arguments: "object.method", object); YAHOO Global Object.
(1) name: A string containing the fully-qualified name of the //call the function
constructor (e.g. YAHOO.widget.Menu). Profiler knows to object.method();
extract everything after the last dot as the short constructor //get specific function information
name. var calls =
(2) owner: The object that owns the function (e.g. YAHOO.tool.Profiler.getCallCount("object.method");
YAHOO.widget for YAHOO.widget.Menu). This argument var avg = YAHOO.tool.Profiler.getAverage("object.method");
may be safely omitted if the name exists in the global scope. var min = YAHOO.tool.Profiler.getMin("object.method");
var max = YAHOO.tool.Profiler.getMax("object.method");
Note: Only constructors that exist on objects can be profiled. Global functions are considered
properties of the window object, so they can be registered but functions declared inside of other //get all function information
functions cannot be registered unless attached to an object. var report =
YAHOO.tool.Profiler.getFunctionReport("object.method");
YUI Library: ProfilerViewer Control 2009-2-6 v2.7
Simple Use Case: Profiling an Object Key ProfilerViewer Configuration Options YAHOO.widget. ProfilerViewer
Field Type Description
Properties
//assuming you have an object with functions called
“myObject”: base string Path to your YUI base directory, to be used by YUI STRINGS static member containing strings
used in the UI; see API docs for the
YAHOO.tool.Profiler.registerObject("myObject", Loader in pulling in dependencies on-demand. format of this object and examples for
myObject); //see Profiler docs for more on how Default: YUI files will be served from how to use this object to internationalize
//to set up your code profiles. yui.yahooapis.com. your ProfilerViewer console.
var pv = new YAHOO.widget.ProfilerViewer(“myEl”); filter function The filter used by ProfilerViewer in determining which
profilerd functions to show in the display. See YAHOO.widget. ProfilerViewer
This code tells the Profiler to profile myObject and tells ProfilerViewer to
create a viewer display in the DOM element whose id is myEl.
Solutions below for more. Methods
maxChart string The maximum number of functions to profile in the
ProfilerViewer will show all profiled functions; use the filter attribute to getBodyEl() returns the element
Functions Chart display. Default: 6. containing the console body (chart and
limit a viewer instance to a subset of profiled functions. Upon
showChart boolean Determines whether or not the Chart Control should table)
instantiation, the ProfilerViewer launcher is rendered: getChart() returns the Chart Control
be used to visualize profiling data. Default: true.
instance (if present)
sortedBy object {key: string, dir: string} The default sort getChartEl() returns the element
column and direction for data in the DataTable. Valid containing the Chart Control and legend
Once the View Profiler Data button is clicked, ProflierViewer will load the keys are: fn, calls, avg, min, max, total, pct. Valid dir getDataTable() returns the DataTable
values are: YAHOO.widget.DataTable.CLASS_ASC Control instance
DataTable and Charts controls and display the viewing console. A
getHeadEl() returns the element
ProfilerViewer console with default options will look like this: and YAHOO.widget.DataTable.CLASS_DESC. containing console header and buttons
swfUrl string Relative path or url to the YUI Charts Control .swf file. getTableEl() returns the element
Defaults to current version hosted on containing DataTable’s DOM structure.
yui.yahooapis.com. refreshData() programmatically refreshes
the data in the console
tableHeight string Height of the DataTable portion of the console.
Default: “15em”.
visible boolean If true, the ProfilerViewer Console will render Dependencies
immediately upon instantiation. Otherwise, just the
launcher will render initially. Default: false. The ProfilerViewer Control
Configuration options should be set in the second argument of the constructor: requires the YUI Loader
var pv = new YAHOO.widget.ProfilerViewer(“myEl”, {visible:true});. (which includes the Yahoo
Global Object and the Get
Key Interesting Moments in ProfilerViewer Utiltiy), Dom Collection,
Event Utility, Profiler, and
Event Description/Fields: Element Utility. (The
renderEvent Event fires when the viewer canvas first renders. No DataTable Control and
arguments passed. Charts Control are brought
refreshDataEvent Event fires when a data refresh is requested through the UI in dynamically by YUI
or programmatically. Loader when the
sortedByChange Event fires when the DataTable is resorted. Argument: ProfilerViewer UI is first
{newValue: new value, oldValue: old value}. made visible.)
visibleChange Event fires when the viewer console is shown/hidden.
Argument: {newValue: new value, oldValue: old value}
Constructor: YAHOO.widget.ProfilerViewer Subscribe: pv.subscribe(“visibleChange”, function(o){});.

YAHOO.widget.ProfilerViewer([str | obj container, obj Solutions:


configuration])
Configure ProfilerViewer to not use the Charts Control:
Arguments:
(1) Container: (Optional) A reference to a DOM element (by ID or direct var pv = new YAHOO.widget.ProfilerViewer(“myEl”,
reference) that will contain the ProfilerViewer display. For best showChart: false);
results, us an element with at least 750px of viewable width. If no Use a filter function to only display profiling data for functions that have been
element is passed, a new element will be created as the first child of called at least once:
the <body> element.
(2) Configuration: (Optional) An optional object containing your desired var pv = new YAHOO.widget.ProfilerViewer(“myEl”,
filter: function(o) {return o.calls > 0;}
configuration options. See Configuration Options section for details.
);
YUI Library: Resize Utility 2009-2-6 v2.7
Simple Use Case: YAHOO.util.Resize Resize Events YAHOO.util.Resize: Methods
Event Fires... getActiveHandleEl() Get the
Markup: HTML reference for the currently active
dragEvent Fires when the DragDrop dragEvent is fired for the config option
<div id="resizeMe"><p>Lorem ipsum resize handle.
draggable. getProxyEl() Get the HTML
dolor</p></div>
startResize Fires when a resize action is started. reference for the proxy, returns null if
Script: beforeResize Fires before every element resize, after the size calculations no proxy.
var resize = new YAHOO.util.Resize('resizeMe'); have been done. Returning false will cancel the resize. getResizeById() Get a resize
resize Fires on event element resize (only fires once when used with object by the HTML id of the element
Creates a Resize instance with default configurations. proxy config setting)
associated with the Resize object.
getStatusEl() Get the HTML
proxyResize Fires on every element resize (only fires when used with proxy reference for the status element.
config setting). getWrapEl() Get the HTML reference
All Resize events are Custom Events (see Element docs); subscribe to these events using their for the wrap element, returns the
subscribe method: resize.on(‘resize,fnMyHandler);. current element if not wrapped.
isActive() Returns true or false if a
resize operation is currently active on
Key Resize Configuration Options the element.

Option Default Description reset() Resets the element to its start


state.
proxy false Resize a proxy element instaed of the actual element . resize() Resizes the element, wrapper,
animate false Indicates whether or not the resize should animate or proxy based on the data from the
sizes (only works with proxy). handlers.
status false Should we show the status tooltip. destroy() Destroys the resize object
handles [‘r’, ‘br’, ‘b’] The handles to use (any combination of): 't', 'b', 'r', 'l', and all of its elements & listeners.

'bl', 'br', 'tl', 'tr'. Can use a shortcut of All. Note: 8 way
resizing should be done on an element that is Dependencies
absolutely positioned.
Constructor: YAHOO.util.Resize ratio false Constrain the resize to a ratio of the current size. The Resize Utility requires
draggable false A convenience method to make the element draggable. Yahoo, Dom, Element,
YAHOO.util.Resize(str | el ref container[, obj Event, Drag and Drop and
Most of Resize options can be set in the constructor's second argument (eg, Animation (optional).
config])
{animate: true}) or at runtime via set (eg, resize.set("animate", true);).
Arguments:
(1) Element: The element to make resizable. Resize Handles
(2) Configuration object: When instantiating Resize, you can
pass all configurations in as an object argument or configure The Resize Utility supports the following handle positions: Top, Bottom,
the instance after instantiation. See Configuration Options Left, Right, Top Right, Top Left, Bottom Right, Bottom Left. The default
section for common configuration object members. handle positions are: Right, Bottom, and Bottom Right.
The default look of the handles is to take up all available space around
Solutions: Customizing the Proxy Element the element to be resized. There are a few configuration options built in
that will alter this look:
The following code demonstrates customization of the proxy
element. • hiddenHandles - Handles are always transparent, the user gets
feedback from the cursor change.
//instantiate Resize:
var myResize = new YAHOO.util.Resize('resizeMe', { • hover - Handles are hidden by default until the user hovers over
proxy: true them, then they appear.
}); • knobHandles - Used for the classic 8-way resize.

//customize proxy during resize via innerHTML: Take a look at the Resize Utility's examples for demos of all of these
myResize.on('startResize', function() { options.
myResize.getProxyEl().innerHTML = 'I am the proxy';
Note: To get the best effect out of using all 8 resize handles, it is
YAHOO.util.Dom.setStyle(myResize.getProxyEl(),
'opacity', ',5'); recommended that the element be absolutely positioned (and if possible
}); be a direct child of the body).
YUI Library: Rich Text Editor 2009-2-6 v2.7
Simple Use Case: YAHOO.widget.Editor Interesting Moments in Rich Text Editor & Toolbar YAHOO.widget.Editor:
See online docs for complete list of Rich Text Editor and Toolbar events. Methods
Markup: Event Fires...
<body class="yui-skin-sam"> render() Causes the toolbar and the
editorContentLoaded Fires after the editor iframe’s document fully loads. editor to render and replace the textarea.
<textarea id="msgpost">Preloaded HTML goes here. editorMouseUp, Fires in response to the corresponding Dom event.
setEditorHTML(string html)
editorMouseDown,
</textarea> editorDoubleClick, Loads HTML into the editor’s body.
</body> editorKeyUp, getEditorHTML() Returns the
editorKeyDown unprocessed HTML from the editor.
Script: beforeExecCommand, Fires at the beginning/end of the execCommand process.
saveHTML() Cleans the HTML with
afterExecCommand Reference YAHOO.util.Element.html#addListener for more details.
var oEditor = new YAHOO.widget.Editor('msgpost', beforeOpenWindow, Fires before/after an editor window is opened.
the cleanHTML method and places the string
{ afterOpenWindow into the textarea.
height: '300px', closeWindow Fires after an editor window is closed. cleanHTML(string html)
toolbarExpanded, Fires when toolbar is expanded/collapsed via the collapse button. Processes the HTML with a few regexes to
width: '500px' toolbarCollapsed clean it up and stabilize the output.
}); buttonClick Fires when a toolbar button receives a click event. clearEditorDoc() Clears the editor
oEditor.render(); All Editor events are Custom Events (see Element docs); subscribe to these events using their doc.
subscribe method: oEditor.on(‘afterNodeChange’,fnMyHandler);. destroy() Destroys the editor along
Creates an Editor instance with default configurations. with all of its elements and objects.
toString() Returns a string
Key Rich Text Editor Configuration Options representing the Editor.
See online docs for complete list of Rich Text Editor configuration options. nodeChange() Handles toolbar
Option (type) Default Description setup, getting the Dom path, and fixing
height, width best guessed size of The height/width of the editor iframe container not nodes.
textarea including the toolbar. execCommand(str command[,
animate false Indicates whether or not the editor should animate
movements.
str arg]) Levels the differences in the
support by various browsers of
disabled false Toggle for the editor’s disabled state. When disabled,
execCommand actions.
design mode is off and a mask is placed over the
iframe so no interaction can take place.
dompath false Toggles the display of the current Dom path below the YAHOO.widget.Toolbar:
editor.
toolbar See editor.js.html The default toolbar config.
Methods
handleSubmit false When true, the editor will attempt to attach a submit
listener to the parent form that would trigger the editor’s addButton(obj config) Add a new
save handler and place the new content back into the button to the toolbar.
textarea before the form is submitted. addButtonGroup(obj config)
Adds a new button group to the Toolbar.
Editor options can be set in the constructor's second argument (eg,
{height: '300px'}) or at runtime via set (eg, oEditor.set("height", "300px");). addButtonToGroup(obj
config) Adds a new button group to a
Constructor: YAHOO.widget.Editor Constructor: YAHOO.widget.SimpleEditor
toolbar group.
addSeparator() Adds a new button
YAHOO.widget.Editor(str | el ref container[, obj separator to the toolbar.
YAHOO.widget.SimpleEditor(str | el ref container[, obj getButtonByValue(str | obj
config])
config]) command) Gets a button instance or a
Arguments: menuitem instance from the toolbar by its
Creates a SimpleEditor instance with default configurations. SimpleEditor value.
(1) Container element: <textarea> element or element id for the
is a lighter version of the Editor Control. disableButton(str | number |
<textarea> that will be transformed into a Rich Text Editor.
(2) Configuration object: When instantiating an Editor, you can obj button) Disables a button in the
toolbar.
pass all configurations in as an object argument or configure enableButton(str | number |
the instance after instantiation. See Configuration Options obj button) Enables a button in the
section for common configuration object members. toolbar.
selectButton(str | number |
Dependencies obj button) Selects a button in the
toolbar.

Editor: Yahoo, Dom, Event, Element, ContainerCore; Animation, Menu deselectButton(str | number
and Button are optional. SimpleEditor: YAHOO, Dom, Event, and | obj button) Deselects a button in the
toolbar.
Element; Animation and ContainerCore are optional.
YUI Library: Selector Utility 2009-2-6 v2.7
Usage: query() Pseudo-classes YAHOO.util.Selector Methods
The Selector Utility supports the use of the pseudo-classes listed here; for more info on these, query(string selector[, node | string
Use query to select one or more DOM elements based on a see the W3C Selectors working draft (http://www.w3.org/TR/css3-selectors/#pseudo-classes). startingNode, bool firstOnly]) the
simple selector string. The query method is used to return all startingNode can be passed in as a string
Pseudo-class Description element ID or as an element reference
nodes that match your criteria unless the firstOnly arg is true. :root The root of the document; in HTML 4.x, this is the HTML element. and defaults to the document element;
:nth- Starting from the bth child, match every ath element. returns an array of matching nodes
var matchingNodes = YAHOO.util.Selector.query child(an+b) filter(arr | nodeList nodes, string
(“ul li a”, “itemList”); selector) returns any nodes that match
:nth-last- An element that has an + b siblings after it. the selector
Note: Will return all anchor elements within list-items of unordered lists who are descendants of child(an+b) test(str | elRef node, string selector)
the element whose id attribute is “itemList”. :nth-of- An element that has an + b siblings before it that share the same returns boolean indicating whether the
type(an+b) element name. node matches the selector criteria
:nth-last-of- An element that has an + b siblings after it that share the same
Usage: YAHOO.util.Selector.query() type(an+b) element name.
Combinators
YAHOO.util.Selector.query(string selector[, node :first-child Same as :nth-child(1) — the first child of a given element.
The Selector Utility supports the
:last-child Same as :nth-last-child(1) — the last child of a given element.
| string startingNode, bool firstOnly]) following four combinators:
:first-of-type Same as :nth-of-type(1) — the first child of a given element with a Descendant
given element name. “”
Arguments: Combinator: “A B”
(1) selector: A string representing the CSS selector you want to :last-of-type Same as :nth-last-of-type(1) — the last child of a given type of the represents an element
specified element. B that has A as an
target.
:only-child An element who is the only child of its parent node. ancestor.
(2) startingNode: The node at which to begin the search :only-of-type An element whose element name is not shared by any sibling nodes.
> Child Combinator: “A >
(defaults to document). Be as specific as possible in choosing :empty An element that has no children. B” represents an
your startingNode to maximize performance. :not() The negation pseudo-class; takes a simple selector as an argument, element B whose
(3) firstOnly: Whether or not to return only the first match. representing an element not represented by the argument. parent node is A.
:contains() An element whose textual contents contain the substring provided in + Direct Adjacent
Returns: the argument. Combinator: “A + B”
(1) Matching Node(s): An array of nodes that match your :checked A radio button or checkbox that is in a checked state. represents an element
selector criteria. If firstOnly is true, this returns a single Notes regarding (an+b) notation: B immediately following
Starting from the bth child, match every ath element. For example, “nth-child(2n+1)” starts from the first a sibling element A.
node or null if no match. element and returns every other element. The “odd” and “even” keywords are supported, so “2n+1” is
equivalent to “odd”. “1n+2” and “n+2” are equivalent. “nth-child(0n+3)” is equivalent to “nth-child(3)”. Zero ~ Indirect Adjacent
value means no repeat matching, thus only the first bth element is matched. “3n+0” is equivalent to “3n”. Combinator: “A ~ B”
Usage: YAHOO.util.Selector.filter() represents an element
B following (not
YAHOO.util.Selector.filter(arr | nodeset nodes, Attribute Operators necessarily
string selector) att=val equality att^=val value starts with val immediately following)
att!=val inequality att$=val value ends with val a sibling element A.
Arguments: att~=val value matches one of att*=val value contains at least one
(1) nodes: A nodeList or an array of nodes from which you want space-delimited words in occurrence of val
to select specific nodes that match your criteria. val Dependencies
(2) selector: A CSS selector against which you want to test and att|=val value starts with val or val- att test for the existence of the
attribute The Selector Utility requires
filter the nodes. only the YAHOO Global
Solutions Object.
Usage: YAHOO.util.Selector.test()
Selector.query(“#nav ul:first-of-type > li:not(.selected)”); //
YAHOO.util.Selector.test(str | elRef node, Starting from the first “ul” inside of “nav” , return all “li”
elements that do not have the “selected” class.
string selector)
Selector.query(“ul:first-of-type > li.selected”, “nav”, true); //
Arguments: Starting from the first “ul” inside of “nav” , return the first
(1) node: A node to test “li” element that has the “selected” class.
(2) selector: A CSS selector against which you want to test ther
Dom.addClass(Selector.query(“#data tr:nth-child(odd)”), “odd” ) //
the node. add the class “odd” to all odd rows within the “data” element.
Note: returns true if the node matches the selector, otherwise false.
YUI Library: S lider 2009-2-13 v2.7
Simple Use Case Interesting Moments in Slider see online docs for complete list YAHOO.widget.Slider:
Factory Methods
Markup: Event Fires... Arguments
getHorizSlider()
<div id="sliderbg"> slideStart ...at the beginning of a none
getVertSlider()
<div id="sliderthumb"><img src="thumbimg"></div> user-initiated change in
</div> getSliderRegion()
the thumb position.
Each method returns a Slider object.
Script: slideEnd ... at the end of a user- none See Constructor section for args list.
var slider = initiated change in the
YAHOO.widget.Slider.getHorizSlider("sliderbg", thumb position. YAHOO.widget.Slider:
"sliderthumb", 0, 200);
change ...each time the thumb int or {x: int, y:int} Properties
Creates a horizontal Slider within the sliderthumb div that can move position changes during a offset from the starting position,
one offset per slider dimension animate (b)
0 pixels left and 200 pixels to the right. user-initiated move. animationDuration (n)
Slider events are Custom Events; subscribe to them by name using the following default 0.2, roughly in seconds
Constructor: YAHOO.widget.Slider syntax: mySlider.subscribe("change", fn);. keyIncrement (n) number of
pixels to move slider on arrow
keypress
YAHOO.widget.Slider.getHorizSlider(str bgid, str Slider Design Considerations
thumbid, int lft/up, int rt/dwn[, int tick]);
YAHOO.widget.Slider:
Arguments for Horizontal and Vertical Sliders: Methods
(1) Background element ID: HTML ID for the slider’s background.
(2) Thumb element ID: HTML ID for the thumb element. getValue()
(3) Left/Up: The number of pixels the thumb can move left or up. getXValue()
(4) Right/Down: The number of pixels the thumb can move right or getYValue()
down. lock()
(5) Tick interval: Number of pixels between each tick mark. setRegionValue(int
newXOffset, int
Region Sliders take four args for range: left, right, up, down. newYOffset, b
A Slider is an implementation of a "finite range control." The range defined skipAnimation)
Solutions by the Slider is incremented in pixels. The maximum range of a slider is setValue(int newOffset, b
the pixel-width of the Slider's background minus the width of the skipAnimation)
Create a vertical Slider with a range of 300 pixels, ticks at 10 px Slider Thumb.
unlock()
intervals, and an initial value of 160:
var slider = Region Sliders: CSS Notes:
YAHOO.widget.Slider.getVertSlider("sliderbg",
A two-dimensional Slider is referred to • Slider background should
"sliderthumb", 0, 300, 10);
as a Region Slider. Region Sliders be position:relative;
slider.setValue(160, true); //set to 160, skip anim
report two values onChange (x offset, y • Slider thumb should be
Create a 300x400 pixel region Slider and set the initial thumb position offset) and have their own method for position:absolute;
to 263 on the x-axis and 314 on the y-axis: setting value in JavaScript: • Slider thumb image should
setRegionValue takes x offset and y not be a background image
var slider = • Alternately use Slider’s skin
offset as arguments, followed by the
YAHOO.widget.Slider.getSliderRegion("sliderbg", CSS file for default
boolean flag for skipping animation.
"sliderthumb", 0, 300, 0, 400); appearance. (see online
Design considerations regarding range
slider.setRegionValue(263, 314, true); docs)
and thumb width apply in both vertical
Assuming an instance of a horizontal Slider in variable mySlider, and horizontal dimensions.
write a handler for its onSlideEnd event:
mySlider.subscribe("slideEnd", function() { Dependencies
alert(this.getValue()); //alerts offset from start
}); Slider requires the YAHOO object, Event, Drag & Drop, Dom, and
(optionally) Animation.
YUI Library: Slider with Dual Thumbs 2009-2-6 v2.7
Simple Use Case Interesting Moments in DualSlider see docs for full list YAHOO.widget.Slider: Factory
Methods
Markup: Event Fires... Arguments
getHorizDualSlider()
<div id="sliderbg"> slideStart ...at the beginning of a Slider instance
getVertDualSlider()
<div id="minthumb"><img src="thumbimg"></div> user-initiated change in
<div id="maxthumb"><img src="thumbimg"></div> either thumb position. Slider instance housing the Each method returns a DualSlider object. See
active thumb Constructor section for args list.
</div>
slideEnd ... at the end of a user- Slider instance
Script: YAHOO.widget.DualSlider:
initiated change in either
var slider = Slider instance housing the Properties
YAHOO.widget.Slider.getHorizDualSlider( thumb position. active thumb
“sliderbg","minthumb",“maxthumb”, 200); change ...each time either of the DualSlider minVal (n) (read only)
thumbs’ positions instance maxVal (n) (read only)
Creates two thumbs (minthumb and maxthumb) that can move within
change during a user- isHoriz (b) (read only)
a horizontal 200 pixel range on a slide background (slidebg).
minSlider (Slider) (read only)
initiated move.
maxSlider (Slider) (read only)
Constructor: YAHOO.widget.DualSlider DualSlider events are Custom Events; subscribe to them by name using the
following syntax: mySlider.subscribe("change", fn);.
minRange (n) (read / write)
YAHOO.widget.Slider.getHorizDualSlider(str bgid, minimum number of pixels the inner edges
str minthumbid, str maxthumbid, int range[, int DualSlider Design Considerations of the thumbs can be apart
tick[,array initVals]]]);
DualSlider is an implementation of a YAHOO.widget.DualSlider:
Arguments for Horizontal and Vertical DualSliders: "finite range control." The range
(1) Background element ID: HTML ID for the slider’s background. Methods
defined by the DualSlider thumbs is
(2) Min Thumb element ID: HTML ID for the thumb element expressed in pixels. setMinValue(int)
representing the lower value. setMaxValue(int)
(3) Max Thumb element ID: HTML ID for the thumb element The maximum range of a slider is setValues(int newMinOffset,
representing the upper value. the pixel-width of the DualSlider's int newMaxOffset,
(4) Range: The maximum pixel offset for the Max Thumb. background minus half the width b skipAnimation)
(5) Tick interval: Number of pixels between each tick mark. of the Min Thumb minus half the
(7) Initial Values: Array containing the desired Min Thumb and Max width of the Max Thumb. YAHOO.widget.DualSlider:
Thumb pixel offsets to assign during instantiation.
Values for each thumb are
Dependencies
calculated according to their center
Solutions point. To quantify the space
DualSlider requires the YAHOO
object, Dom, Event, Drag & Drop,
Create a vertical DualSlider with a 300 pixel range, ticks at 10 px between the thumbs, use this and (optionally) Animation.
formula:
intervals, and initial values of 160 and 220:
var slider =
CSS Notes:
innerDiff = maxVal - minVal -
YAHOO.widget.Slider.getVertDualSlider("sliderbg" (maxThumbWidth/2) - • DualSlider background should
, "minthumb", “maxthumb”, 300, 10, [160,220] ); be position:relative;
(minThumbWidth/2)
• Slider thumbs should be
Assuming an instance of a DualSlider in variable mySlider, write a position:absolute;
handler for its change event: • Slider thumb image should not
be a background image
mySlider.subscribe("change", function() {
alert(“MIN: “+this.minVal+” MAX: “+this.maxVal);
});
YUI Library: TabView 2009-2-6 v2.7
Simple Use Case: YAHOO.widget.TabView Key Interesting Moments in TabView YAHOO.widget.TabView:
See online docs for a complete list of TabView's Events; see Solutions for how to access Event Fields. Properties
Markup (optional, using standard module format): Event: Event Fields: CLASSNAME
<div id="mytabs" class=”yui-navset”> TAB_PARENT_CLASSNAME
available type (s), target (el)
<ul class="yui-nav"> CONTENT_PARENT_CLASSNAME
<li><a href=” … ”>tab one</a></li> beforeActiveTabChange type (s), prevValue (Tab), newValue (Tab)
<li><a href=” … ”>tab two</a></li> contentReady type (s), target (el) YAHOO.widget.TabView:
</ul> activeTabChange type (s), prevValue (Tab), newValue (Tab)
All TabView events are Custom Events (see Event Utility docs); subscribe to these events Methods
<div class=”yui-content”>
using “addListener”: (e.g. myTabs.addListener(‘activeTabChange”, fn); ). addTab(Tab)
<div><p>Tab one content.</p></div>
<div><p>Tab two content.</p></div> removeTab(Tab)
</div> Key Interesting Moments in Tab getTab(i)
</div> See online docs for a complete list of Tab's Events; see Solutions for how to access Event Fields. getTabIndex(Tab)
Event: Event Fields: contentTransition()
Script: beforeContentChange type (s), prevValue (s), newValue (s) set(option, value)
var myTabs = new YAHOO.widget.TabView("mytabs"); beforeActiveChange type (s), prevValue (Tab), newValue (Tab) get(option)
Creates a TabView instance using existing markup. contentChange type (s), prevValue (s), newValue (s)
activeChange type (s), prevValue (Tab), newValue (Tab) YAHOO.widget.
Constructor: YAHOO.widget.TabView
All TabView events are Custom Events (see Event Utility docs); subscribe to these events Tab: Properties
using addListener (e.g. myTabs.addListener(‘activeChange”, fn); ).
LABEL_TAGNAME
YAHOO.widget.TabView(str|HTMLElement|obj el[,
obj config]);
Key TabView Configuration Options ACTIVE_CLASSNAME
See online docs for complete list of TabView options. DISABLED_CLASSNAME
Arguments: LOADING_CLASSNAME
Option (type) Default Description
(1) el: HTML ID or HTMLElement of existing markup to use when activeTab null The currently active Tab.
building tabView. If neither, this is treated as the (Tab) YAHOO.widget.
Configuration object. orientation “top” The orientation of the Tabs relative to the Tab: Methods
(2) Configuration Object: JS object defining configuration TabView. (“top”, “right”, “bottom”, “left”)
set(option, value)
properties for the TabView instance. See Configuration get(option)
element null HTMLElement bound to TabView
section for full list.
TabView options can be set in the constructor's second argument (eg, {activeTab:
tabInstance}) or at runtime via set (eg, myTabs.set("activeTab", tabInstance);).
Dependencies
Solutions Key Tab Configuration Options
See online docs for complete list of Tab configuration options.
TabView requires the
Listen for a TabView Event and make use of the Event's fields. Option (type) Default Description YAHOO object, Event,
Dom, and Element.
var tabView = new YAHOO.widget.TabView('demo'); active (b) false Whether or not the Tab is active.
var handleActiveTabChange = function(e) { disabled (b) false Whether or not the Tab is disabled.
alert(e.newValue); label (s) null The text (or innerHTML) to use as the Tab’s
}; label.
tabView.addListener(‘activeTabChange’, content (s) null The HTML displayed when the Tab is active.
handleActiveTabChange); labelEl (el) null The HTMLElement containing the label.
Add a new Tab with with dynamic source to an existing contentEl (el) null The HTMLElement containing the
TabView instance: contentEl.
tabView.addTab(new YAHOO.widget.Tab({label: ‘My dataSrc (s) null Url to use for retrieving content.
Label’, dataSrc: ‘mySource.html’, cacheData (b) false Whether or not data retrieved from dataSrc
cacheData:true})); should be cached or reloaded each time the
Tab is activated.
Remove an existing tab from a TabView:
Element (el) null HTMLElement bound to Tab
tabView.removeTab(tabView.getTab(1)); Tab options can be set in the constructor's second argument (eg, {disabled: true}) or at
runtime via set (eg, myTab.set("disabled", true);).
YUI Library: TreeView 2009-2-6 v2.7
Simple Use Case Interesting Moments in TreeView see docs for complete list YAHOO.widget.
TreeView: Properties
var tree = new YAHOO.widget.TreeView("treeDiv1"); Event Fires... Arguments
id (str)
var root = tree.getRoot(); expand ...before a node expands; Node obj expanding
var tmpNode = new YAHOO.widget.TextNode("mylabel", return false to cancel. node
collapse ...before a node collapses; Node obj collapsing YAHOO.widget.
root);
tree.render(); return false to cancel node TreeView: Methods
clickEvent ...when node is clicked Node clicked and event collapseAll()
Places a TreeView Control in the HTML element whose ID attribute is dblClickEvent ... when node is double Node clicked and event render()
"treediv1"; adds one node to the top level of the tree and renders. clicked expandAll()
enterKeyPressed ... when Enter key is pressed Node obj with the focus getNodesByProperty()
when a node has the focus getRoot()
Constructor: YAHOO.widget.TreeView popNode(node) returns detached
TreeView events are Custom Events; subscribe to them by name using the following node, which can then be reinserted

YAHOO.widget.TreeView(str | element target, syntax: tree.subscribe("expand", fn);. removeChildren(node)


removeNode(node, b
oConfig); autorefresh)
TreeView object definition setDynamicLoad(fn)
Arguments:
var tree = new YAHOO.widget.TreeView("treeDiv1", [ getTreeDefinition()
(1) Element id or reference: HTML ID or element reference for the "label0",
element into which the Tree's DOM structure will be inserted. If {type:"text", label: "label1", … , children: [… ]}, … YAHOO.widget.Node:
the given element contains a series of nested ordered or ]);
Properties
unordered lists, they will be used to build the tree. Tree definition is an array containing node definitions. If node
Inherited by Text, Menu, & HTML nodes
(2) Object literal: an object containing the full tree definition definition is a string, a TextNode is build. If an object, it should have a
data (obj)
type property of “text”, “menu” or “html” or the full name of a expanded (b)
Nodes: Text, Menu, HTML, Date node type (i.e.: “HTMLNode”) plus any other properties as would be hasIcon (b)
provided to a Node constructor. Each node can have an optional href (str)
Node (abstract base class for all others) isLeaf (b)
children property with further node definitions.
iconMode (i)
YAHOO.widget.TextNode(obj | str oData, Node obj labelStyle (s) Text/MenuNodes only.
oParent); TreeView from existing markup
Use to style label area, e.g. for custom
icons. Use contentStyle property
for HTMLNodes
Arguments: <ul><li>List 0 nextSibling (node obj)
(1) Associated data: A string containing the node label or an object <ul><li>List 0-0</li> parent (node obj)
containing values for any public properties of the node … previousSibling (node obj)
</ul></li> target (str)
(2) Parent node: The node object of which the new node will be a <li><a href="www.elsewhere.com">elsewhere</a></li> tree (TreeView obj)
child; for top-level nodes, the parent is the Tree's root node. </ul> editable (b)
TextNode (for simple labeled nodes):
YAHOO.widget.Node:
If oData is a string it will be used as the label. If an object, it should Solutions: Dynam ically load child nodes:
Methods
contain a label property. If no oData.href is provided, clicking on fnLoadData = function(oNode, fnCallback) { Inherited by Text, Menu, & HTML nodes
the TextNode's will invoke the node's expand method. //create child nodes for oNode
appendTo()
var tmp = new YAHOO.widget.TextNode("lbl", oNode); collapse()
MenuNode (for auto-collapsing node navigation): fnCallback(); //then fire callback} collapseAll()
var tree = new Yahoo.widget.TreeView(targetEl); expand()
MenuNodes are identical to TextNodes in construction and behavior, tree.setDynamicLoad(fnLoadData); expandAll()
except that only one MenuNode can be open at any time for a given var root = tree.getRoot(); getEl() returns node's wrapper <div>
level of depth. var node1 = new YAHOO.widget.TextNode("1st", root); element
getHTML() includes children
var node2 = new YAHOO.widget.TextNode("2nd", root);
HTMLNode (for nodes with customized HTML for labels): getNodeHTML() sans children
node2.isLeaf = true; // leaf node, not dynamic hasChildren()
tree.render(); insertBefore()
A string containing markup for the node's label or an object containing
insertAfter()
at least an html property isDynamic()
Dependencies isRoot()
DateNode (for nodes containing dates): setDynamicLoad()
TreeView requires Yahoo, Dom and Event. Animation is optional; the toggle()
Same as TextNode, will use Calendar widget for cell editing the Calendar Control may be used for date editing.
YUI Library: Uploader 2009-2-6 v2.7
Instantiating the Uploader Simple Use Case YAHOO.widget.Uploader
Properties:
<div id="upldrContainer" myUploader.setAllowMultipleFiles(true);
style=”width:200px;height:50px”></div> SWFURL (str)
<script> myUploader.setFileFilters([{description:"Images", extensions:"*.jpg,
var myUploader = new YAHOO.widget.Uploader(
"upldrContainer", "btnSprite.jpg”);
*.gif"}]); YAHOO.widget.Uploader
</script> Events:
myUploader.addListener("fileSelect", onFileSelect);
Instantiates a new Uploader object, myUploader, which is contentReady
bound to a div whose id attribute is 'upldrContainer'. function onFileSelect (event:Object) { fileSelect
The result will be a Flash button, skinned by btnSprite.jpg myUploader.uploadAll("YOUR UPLOAD URL"); uploadStart
(an image of four-equal sized button skins stacked } uploadProgress
vertically: up, hover, down, disabled). If no skin URL is Sets the permission to browse for multiple files, and allows the users to select files with uploadCancel
passed, the uploader will render as a transparent button. In either jpg or gif extension (on Windows, the filtering is suggestive, rather than strict.) uploadComplete
both cases, clicking the button invokes the “Browse” dialog. The “Browse” dialog with these settings comes up when the uploader control is clicked. uploadCompleteData
When files are selected, they are queued and uploaded to the specified URL using uploadError
Constructor automatic queue management.
When transparent:
YAHOO.widget.Uploader(str html id,
str btnSkinURL);
Solutions mouseUp
mouseDown
Arguments: Track upload progress and log it in the YUI Logger (must be included on the page): rollOver
(1) HTML element (string or object): A reference to an myUploader.addListener("uploadProgress", onUploadProgress); rollOut
HTML id string or element object binds the Uploader to function onUploadProgress (event:Object) { click
an existing page element. This parameter is required. YAHOO.log(event.id + ": " + event.bytesLoaded + "/" +
(2) Button Skin URL (string): A url of an image event.bytesTotal);
consisting of four equal-sized button skins stacked YAHOO.widget.Uploader
}
vertically. The top-to-bottom order is: up, hover, Methods:
down, disabled. This parameter is optional. setAllowLogging()
Send custom variables in the same POST request as the file submission:
myUploader.upload("file0", "YOUR UPLOAD URL", "POST", {var1: setAllowMultiple()
Limitations "foo", var2: "bar", var3: "baz"}); setFileFilters()
enable()
1. The Uploader can only send data to servers in the same Modify the file form field name from the default “Filedata”: disable()
security sandbox as the uploader.swf file. If myUploader.upload("file0", "YOUR UPLOAD URL", POST, null, upload()
uploader.swf hosted by yui.yahooapis.com is used, "DifferentFileFieldName"); uploadAll()
then the server must contain a cross-domain permissions cancel()
file allowing yui.yahooapis.com to upload files. clearFileList()
Accept the file upload using PHP on the server side:
2. The intended behavior of the uploader is not to send any
cookies with its requests. As a workaround, we suggest <?php
either using a cookieless upload method or appending foreach ($_FILES as $fieldName => $file) {
document.cookie to the upload request. move_uploaded_file($file['tmp_name'], "./" . $file['name']);
3. When the uploader is rendered as a transparent layer, it echo (" ");
does not respond to keyboard. When the uploader is }
rendered as an image, it receives "Space" and "Enter" key exit();?>
presses as triggers, but only if the focus is on the uploader
component itself. Dependencies
4. The uploader does not support basic authentication.
5. The behavior when working through a proxy server is
inconsistent and unreliable. Also, when uploading to YUI: Yahoo Global Object, Dom, Event, Element and uploader.swf.
HTTPS servers, be aware that Flash does not support self- Client: Flash 9.0.45 or later installed on their browser.
signed certificates.
YUI Library: The YAHOO Global Object 2009-2-6 v2.7
Simple Use Case: YAHOO Object YAHOO Object: Default Members YAHOO.lang Methods
See online docs for complete documentation on each default member of the YAHOO object. dump(obj or arr) returns string
In its simplest usage, the YAHOO global object requires no Member Type Description representation
implementer action; it serves as a container and provider of utility isArray(any) returns boolean
env object Environment object. Contains information about what isBoolean(any) returns boolean
methods to all other components of the YUI Library. YUI modules are loaded and provides a method for isFunction(any) returns boolean
obtaining version information. isNull(any) returns boolean
isNumber(any) returns boolean
Usage: YAHOO.namespace() example object An empty object used as a namespace for example
isObject(any) returns boolean
implementations.
isString(any) returns boolean
YAHOO.namespace(str namespace) lang object Contains utility methods. Full list at right. isUndefined(any) returns boolean
util object Namespace for YUI utilities. Do not add your own hasOwnProperty(obj, property)
Arguments: members to this object returns boolean
(1) namespace: A string containing a single namespace (e.g. tool object Namespace for developer tools like YUITest. Do not augmentObject() general mixin function
“myproduct”) or a deeper namespace (e.g. add your own memebers to this object. augmentProto() see usage section
extend() see usage section
“myproduct.weatherModule”). Namespace objects are widget object Namespace for YUI controls (widgets). Do not add isValue(any) returns false for
created within the YAHOO object. your own members to this object. null/undefined/NaN, else true — note that
log method Calls YAHOO.widget.Logger.log; prevents log false has value and returns true
Note: Be careful when naming packages. JavaScript reserved words may work as property
names in some browsers and not others. messages from throwing errors when the Logger merge(obj1, obj2, …) returns object with
all properties of all args
Control is not present. substitute() see docs
register method Registers a module with the YAHOO object.
Usage: YAHOO.lang.augmentObject() trim(string) removes leading/trailing space

Usage: YAHOO.lang.extend() YAHOO.env Method:


YAHOO.lang.augmentObject(fn receiver, fn
supplier[, str property1, str property2, … , getVersion(str yuimodulename)
YAHOO.extend(obj subclass, obj superclass[, obj returns module info; see below
str propertyn])
overrides])
Arguments: Module Info
Arguments:
(1) receiver: The object to be augmented.
(1) subclass: The object you're using to extend the base object. YAHOO.env.modules is an
(2) supplier: The object serving as the source of the object indexed by module
(2) superclass: The base object being extended by the "subclass".
augmentation. name; each member contains
(3) overrides: An object whose members will be added to the subclass information about a single YUI
(3-n) properties: By default, YAHOO.lang.augmentObject will
prototype, overriding members of the same name if they exist on the module. Module info objects
apply all members of the supplier object to the receiver if the contain the following
superclass prototype.
receiver doesn’t already have them; arguments 3 through n information:
can be used to supply string member names that designate name str module name
the specific members to be augmented from the supplier to Solutions version str last loaded
version
the receiver.
YAHOO_config is not included as part of the YUI library. Instead it is an build n last loaded build
Note: The default operation, in which all of the supplier's members are applied to the receiver, versions arr all loaded
YAHOO.lang.augment will avoid overwriting existing members on the receiver. If you specify
object that can be defined by the implementer immediately before versions
supplier members to use for augmentation (via arguments 3 through n), the augmentation will including the YUI library. Use YAHOO_config to set up a listener that builds arr all loaded builds
overwrite those members if they already exist on the receiver. mainClass fn reference to main
fires when YUI components are loaded: class for this module
var YAHOO_config = {
Usage: YAHOO.lang.augmentProto()
YUI module names: animation,
listener: function(moduleInfo) { autocomplete, base, button,
//executes when any YUI module loads, including YAHOO calendar, colorpicker, connection,
YAHOO.lang.augmentProto(fn receiver, fn supplier[, str container, containercore, datasource,
property1, str property2, … , str propertyn]) object datatable, dom, dragdrop, editor,
} element, event, fonts, grids, history,
This function is symmetrical with YAHOO.lang.augmentObject } imageloader, json, logger, menu,
profiler, profilerviewer, reset,
(see above); however, it augments only from the supplier’s Note: See Module Info table at right for the format of object passed to your listener function. simpleeditor, slider, stylesheet,
prototype to the receiver’s prototype. Instance members are not tabview, treeview, yahoo, yuiloader,
copied from the supplier to the receiver. Get version information for a YUI component that has been loaded on yuitest.
the page:
Dependencies var YAHOO.env.getVersion("animation"); //returns module info
object
The YAHOO Global Object is a dependency for all YUI components; it
has no dependencies of its own.
YUI Library: YUI Loader Utility 2009-2-6 v2.7
Simple Use Case: YAHOO.util.YUILoader Key YUI Loader Configuration Options YAHOO.util.YUILoader:
Option (type) Default Description Properties
Markup:
<script src="yuiloader-beta.js"></script> allowRollup (b) true Allow aggregate files (e.g., utilities.js) where See also configuration options; all
appropriate? (improves performance) configuraton options can be treated as
Script: base (s) current build dir on Base directory for YUI build. instance members.
//instantiate Loader: yui.yahooapis.com
loader = new YAHOO.util.YUILoader(); combine (b) false Use the combo service on the Yahoo! CDN to inserted obj list of modules inserted
reduce the number of HTTP requests. by the YUILoader instance
//identify the components you want to load:
loader.require("colorpicker", "treeview"); charset (s) utf8 The charset attribute for new node(s). Default: utf-8 sorted arr listed of sorted
dependencies; available after insert or
filter (s | o) null Filter that can be applied to YUILoader filenames
//configure the Loader instance calculate is called
prior to loading. Use 'DEBUG' for debug versions of
loader.loadOptional = true;
YUI files YAHOO.util.YUILoader:
//Load files using the insert() method. Insert() takes an optional loadOptional false Load all optional dependencies for the required
//configuration object, and in this case we are setting up an onSuccess
components? Methods
//callback. Your callback will be executed once all required files are (b)
//loaded. onFailure (f) null Callback function fired if an insert operation fails. addModule(o) adds non-YUI
loader.insert({ onSuccess: function() { Callback function fired each time a resource loads
//this is your callback function; you can use
onProgress (f) null module; obj argument specifies all needed
successfully. metadata for new module
//this space to call all of your instantiation
//logic for the components you just loaded. onSuccess (f) null Callback function to run when loading of all required calculate() calculates the list of
}}); components and dependencies is complete. needed modules based on required
components but does not insert them in the
onTimeout (f) null
Sets up a YUI Loader instance, configures it to load Color Picker and page
timeout (i) 0 The number of millisecond to wait for a resource to
TreeView, and then executes the load. load.
insert(o) calculates needed modules,
inserts them, fires o.onSuccess if that is
require (arr) true Array of required YUI components, each of which is supplied
Constructor: YAHOO.util.YUILoader a string representing the modulename for the
component.
YAHOO.util.YUILoader(obj config) skin (o) by default, the YUI Object which allows you to specify a global Components &
Sam Skin is defaultSkin and per-component overrides.
Arguments: applied to skinned
See User’s Guide for full syntax. Module Names
components
(1) Configuration object: When instantiating YUI Loader, you can pass null for insert(); Only needed for non-YUI scripts. This is the variable
varName (s) YUI Loader refers to YUI components
all configurations in as an object argument or configure the instance “YAHOO” for defined by the exterrnal script whose presence by their unique module names —
after instantiation. See Configuration Options section for common sandbox()
indicates load-completion; for sandbox(), this is the strings by which components are
configuration object members. root variable for the loaded library. referenced within YUI. Here is the full
list of YUI module names:
insertBefore null Element reference or id of a node that should be
(s | el) used as the insertion point for new nodes. This is animation, autocomplete, base,
Using YUI Loader to Load Non-YUI Files useful for making sure CSS rules are parsed in the button, calendar, carousel, charts,
See online docs for full syntax and example using addModule(). correct order (place your style overrides in a single colorpicker, connection,
style block and insertBefore this node). container, container_core, cookie,
YUI Loader’s addModule method can be used to extend YUI Loader to YUI Loader options can be set in the constructor's second argument (eg, datasource, datatable, dom,
add non-YUI modules. addModule takes an object argument with the {base: ‘../../’}) or at runtime on a YUILoader instance (eg, oLoader.base = dragdrop, editor, element, event,
following members: ‘../../’). fonts, get, grids, history,
imagecropper, imageloader, json,
name (s) String modulename. layout, logger, menu, paginator,
type (s) String moduletype (eg, “js” or “css”).
Solutions profiler, profilerviewer, reset,
resize, selector, simpleeditor,
path (s) Path to source file, including file name; will be prefixed with var loader = new YAHOO.util.YUI Loader(); slider, stylesheet, tabview,
instance's base path setting. loader.sandbox({ treeview, uploader, yahoo,
require: ["treeview"], // what to load yuiloader, yuitest.
fullpath (s) Full URI to module file. Supersedes path. base: '../../build/', // relative path to library files
varName (s) If module is JavaScript, a variable name (as string) that will loadOptional: true, // pull in optional components
be defined by the loaded script; alternatively, use
// Executed once the sandbox is successfully created:
Dependencies
YAHOO.register.
onSuccess: function(o) {
requires (arr) Array of required dependencies, with each member a string YUI Loader has no
var myYAHOO = o.reference; //ref to private YAHOO
module name. dependencies. Its package
// TreeView in myYAHOO can now be used; note that
optional (arr) Array of optional dependencies, with each member a string includes the Yahoo Global Object
// YAHOO.widget.TreeView may not exist!
module name. myYAHOO.util.Event.onAvailable("treeEl",function() { and the Get Utility. Do not load
var tree = new myYAHOO.widget.TreeView("treeEl"); the YUI Loader file and the Yahoo
skinnable (b) Does this component have a skin CSS file (in the standard
}); Global Object or Get Utility files
skin-CSS directory?
}, on the same page.
after (arr) Array of modules that are not dependencies, but need to be
});
included above this component if present.
YUI Library: YUI Test Utility 2009-2-6 v2.7
Simple Use Case: TestCase Object Key Events in YUITest YAHOO.tool.TestSuite
See online docs for full list of custom events, including TestSuite- and TestRunner-level events. Methods:
Create a TestCase object with desired tests, add your TestCase All YUITest events are subscribed to at the TestRunner level; e.g.:
add(obj testCase or testSuite) adds a
to the TestRunner object, and run the test: YAHOO.tool.TestRunner.subscribe(YAHOO.tool.TestRunner.TEST_FAIL_EVENT, myFn);.
testCase or testSuite object to a testSuite
Test-level Events
//set up a test case:
var oTestCase = new YAHOO.tool.TestCase({ Event: Fires: YAHOO.tool.TestRunner
name: "Simple Math", TEST_PASS_EVENT When an individual test passes. Methods:
! testEquality: function () { TEST_FAIL_EVENT When an individual test fails. add(obj testCase or testSuite) adds a
! YAHOO.util.Assert.areEqual(4, (2+2), "2+2=4"); testCase or testSuite object to the list of
}; Argument Data Object for Test-level Events:
items to run
}); type Type of event. clear() removes all test objects from the
runner
//add the test case to the TestRunner: testCase The testCase object to which this test belongs. run() runs all testCase and testSuites
YAHOO.tool.TestRunner.add(oTestCase); testName The string name of this test. currently queued in the TestRunner
YAHOO.tool.TestRunner.run(); //run the test TestCase-level Events
YAHOO.tool.TestCase
Event: Fires:
Methods:
Key Members of the TestCase Object TEST_CASE_BEGIN_EVENT Before the TestCase is run.
TEST_CASE_COMPLETE_EVENT After the TestCase is run. wait([fn segment, int delay]) causes the
name The name of the TestCase. This will be visible in the TestCase to delay the specified number
logging of TestCase events. Argument Data Object for TestCase-level Events: of milliseconds before segment is
executed
type Type of event. resume([fn segment]) resmes a paused
testname A function that tests functional code via one or more
testCase Current TestCase instance. test; if segment is omitted, the test
assertions; name must begin with the string “test”. A automatically passes
TestCase can have one or more test members. results passed Number of tests that passed.
(TEST_CASE_END event
setUp Method that prepares your test case to run by, for only)
failed Number of tests that failed. YAHOO.util.UserAction
example, creating needed data constructs or objects. testname result pass or fail. Methods:
tearDown Method that nulls out variables in use by the TestCase, message String returned by the test. click(obj target, obj options) simulates a
detaches event handlers, etc. Note: TestSuite- and TestRunner-level events are also available, containing summary data in click on the target
addition to specific TestCase results objects. See online docs for full details. mousedown(obj target, obj options)
_should Special object that provides granular configuration of the simulates a mousedown on the target
test case. It can have the following members: mouseup(obj target, obj options)
Assertions simulates a mouseup on the target
ignore A name:value pair consisting of a mouseover(obj target, obj options)
Assertions are accessed via YAHOO.util.Assert simulates a mouseover on the target
testname and Boolean indicating whether
Equality assertions: isTypeOf assertion: mouseout(obj target, obj options)
to ignore the test (e.g.: ignore: simulates a mouseout on the target
{testOne : true /*ignore areEqual(expected, actual) isTypeOf(sType, sTest, mousemove(obj target, obj options)
testOne*/}. areNotEqual(expected, actual) sFailureMessage) simulates a mousemove on the target
equivalent to == test YAHOO.util.Assert.isTypeOf(“stri keydown(obj target, obj options)
error A name:value pair consisting of a Sameness assertions:
ng”, 5, “Expected string.”); simulates a keydown on the target
testname and Boolean indicating whether //fails keyup(obj target, obj options) simulates
areSame(expected, actual) a keyup on the target
the test is should fail: areNotSame(expected, actual) isInstanceOf assertion: keypress(obj target, obj options)
equivalent to === test isInstanceOf(oConstructor, simulates a keypress on the target
error: {testTwo : true oTestObject, sFailureMessage)
/*testTwo should fail*/} Data-type assertions: YAHOO.util.Assert.isInstanceOf(S
isArray(arg) tring, “Madrone”, “Expected Dependencies
Or, a specific error string can substitute isBoolean(arg) string.”); //passes
isFunction(arg) can be used to test non-native objects, too The YUI Test Utility requires the
for the Boolean:
isNumber(arg) Yahoo Global Object, Dom
Special Value Assertions: Collection, Event Utility, and
error: {testTwo : “Expected isObject(arg) object and function return true isFalse, isTrue, isNaN, isNotNaN, Logger Control. The Logger’s
string.” /*testTwo should isString(arg) isNull, isNotNull, isUndefined, CSS file and the YUI Test CSS
fail with this specific isNotUndefined file are also required.
error message*/}. YAHOO.util.Assert.isNull(7,
All TestCase configurations should be passed into the TestCase constructor as an object literal;
“Expected null.”); //fails
see Simple Use Case.

Вам также может понравиться