Professional Documents
Culture Documents
This documentation is released under a Attribution-NonCommercial-ShareAlike 3.0 License. copyright 2006-2008 Valerio Proietti
Table of Contents
Core..................................................................................................................................................................................1 Function: $chk............................................................................................................................................................1 Function: $clear..........................................................................................................................................................1 Function: $defined.....................................................................................................................................................2 Function: $arguments................................................................................................................................................2 Function: $empty.......................................................................................................................................................3 Function: $lambda.....................................................................................................................................................3 Function: $extend.......................................................................................................................................................4 Function: $merge.......................................................................................................................................................4 Function: $each..........................................................................................................................................................5 Function: $pick...........................................................................................................................................................6 Function: $random.....................................................................................................................................................6 Function: $splat..........................................................................................................................................................7 Function: $time...........................................................................................................................................................7 Function: $try.............................................................................................................................................................8 Function: $type...........................................................................................................................................................9 Hash: Browser...............................................................................................................................................................10 Native: Array.................................................................................................................................................................11 Array Method: each.................................................................................................................................................11 Array Method: every...............................................................................................................................................12 Array Method: filter................................................................................................................................................13 Array Method: clean................................................................................................................................................13 Array Method: indexOf...........................................................................................................................................14 Array Method: map.................................................................................................................................................14 Array Method: some................................................................................................................................................15 Array Method: associate..........................................................................................................................................16 Array Method: link..................................................................................................................................................17 Array Method: contains..........................................................................................................................................17 Array Method: extend.............................................................................................................................................18 Array Method: getLast............................................................................................................................................18 Array Method: getRandom.....................................................................................................................................19 Array Method: include............................................................................................................................................19 Array Method: combine..........................................................................................................................................20 Array Method: erase................................................................................................................................................20 Array Method: empty..............................................................................................................................................20 Array Method: flatten..............................................................................................................................................21 Array Method: rgbToHex........................................................................................................................................21 Utility Functions............................................................................................................................................................23 Function: $A.............................................................................................................................................................23 Native: Function............................................................................................................................................................24 Function Method: create.........................................................................................................................................24 Function Method: pass............................................................................................................................................25 Function Method: attempt......................................................................................................................................26 Function Method: bind............................................................................................................................................26 Function Method: bindWithEvent.........................................................................................................................27 Function Method: delay...........................................................................................................................................27 Function Method: periodical...................................................................................................................................28 Function Method: run..............................................................................................................................................29 Native: Number.............................................................................................................................................................30 Number Method: limit.............................................................................................................................................30 Number Method: round...........................................................................................................................................30 Number Method: times............................................................................................................................................31
Number Method: toFloat.........................................................................................................................................31 Number Method: toInt.............................................................................................................................................32 Native: String................................................................................................................................................................33 String Method: test..................................................................................................................................................33 String Method: contains..........................................................................................................................................33 String Method: trim.................................................................................................................................................34 String Method: clean................................................................................................................................................34 String Method: camelCase......................................................................................................................................35 String Method: hyphenate.......................................................................................................................................35 String Method: capitalize........................................................................................................................................35 String Method: escapeRegExp................................................................................................................................36 String Method: toInt................................................................................................................................................36 String Method: toFloat............................................................................................................................................37 String Method: hexToRgb.......................................................................................................................................37 String Method: rgbToHex.......................................................................................................................................38 String Method: stripScripts....................................................................................................................................38 String Method: substitute........................................................................................................................................39 Native: Hash..................................................................................................................................................................40 Hash Method: constructor......................................................................................................................................40 Hash Method: each..................................................................................................................................................40 Hash Method: has....................................................................................................................................................41 Hash Method: keyOf................................................................................................................................................42 Hash Method: hasValue...........................................................................................................................................42 Hash Method: extend...............................................................................................................................................43 Hash Method: combine............................................................................................................................................43 Hash Method: erase.................................................................................................................................................44 Hash Method: get.....................................................................................................................................................44 Hash Method: set......................................................................................................................................................45 Hash Method: empty................................................................................................................................................46 Hash Method: include..............................................................................................................................................46 Hash Method: map...................................................................................................................................................46 Hash Method: filter..................................................................................................................................................47 Hash Method: every.................................................................................................................................................48 Hash Method: some..................................................................................................................................................49 Hash Method: getClean...........................................................................................................................................50 Hash Method: getKeys.............................................................................................................................................50 Hash Method: getValues..........................................................................................................................................50 Hash Method: toQueryString.................................................................................................................................51 Utility Functions............................................................................................................................................................52 Function: $H.............................................................................................................................................................52 Native: Event.................................................................................................................................................................53 Event Method: constructor.....................................................................................................................................53 Event Method: stop..................................................................................................................................................54 Event Method: stopPropagation.............................................................................................................................54 Event Method: preventDefault...............................................................................................................................55 Hash: Event.Keys..........................................................................................................................................................57 Native: Class..................................................................................................................................................................58 Class Method: constructor......................................................................................................................................58 Class Method: implement........................................................................................................................................60 Class: Chain...................................................................................................................................................................61 Chain Method: constructor.....................................................................................................................................61 Chain Method: chain...............................................................................................................................................62 Chain Method: callChain........................................................................................................................................62 Chain Method: clearChain......................................................................................................................................63
Class: Events..................................................................................................................................................................64 Events Method: addEvent.......................................................................................................................................64 Events Method: addEvents......................................................................................................................................65 Events Method: fireEvent........................................................................................................................................66 Events Method: removeEvent.................................................................................................................................66 Events Method: removeEvents...............................................................................................................................67 Class: Options................................................................................................................................................................68 Options Method: setOptions...................................................................................................................................68 Native: Window.............................................................................................................................................................70 Function: $................................................................................................................................................................70 Function: $$..............................................................................................................................................................71 Native: Element.............................................................................................................................................................72 Element Method: constructor.................................................................................................................................72 Element Method: getElement..................................................................................................................................73 Element Method: getElements................................................................................................................................73 Element Method: getElementById.........................................................................................................................74 Element Method: set................................................................................................................................................74 Element Method: get................................................................................................................................................76 Element Method: erase............................................................................................................................................76 Element Method: match..........................................................................................................................................77 Element Method: inject...........................................................................................................................................78 Element Method: grab.............................................................................................................................................80 Element Method: adopt...........................................................................................................................................81 Element Method: wraps..........................................................................................................................................82 Element Method: appendText.................................................................................................................................82 Element Method: dispose........................................................................................................................................83 Element Method: clone............................................................................................................................................83 Element Method: replaces.......................................................................................................................................84 Element Method: hasClass......................................................................................................................................85 Element Method: addClass.....................................................................................................................................86 Element Method: removeClass...............................................................................................................................86 Element Method: toggleClass..................................................................................................................................87 Element Method: getPrevious.................................................................................................................................88 Element Method: getAllPrevious............................................................................................................................88 Element Method: getNext........................................................................................................................................88 Element Method: getAllNext...................................................................................................................................89 Element Method: getFirst........................................................................................................................................89 Element Method: getLast........................................................................................................................................89 Element Method: getParent....................................................................................................................................90 Element Method: getParents...................................................................................................................................90 Element Method: getChildren.................................................................................................................................90 Element Method: hasChild......................................................................................................................................90 Element Method: empty..........................................................................................................................................91 Element Method: destroy........................................................................................................................................92 Element Method: toQueryString............................................................................................................................92 Element Method: getSelected..................................................................................................................................93 Element Method: getProperty.................................................................................................................................93 Element Method: getProperties..............................................................................................................................94 Element Method: setProperty.................................................................................................................................94 Element Method: setProperties...............................................................................................................................95 Element Method: removeProperty.........................................................................................................................96 Element Method: removeProperties.......................................................................................................................96 Element Method: store.............................................................................................................................................97 Element Method: retrieve........................................................................................................................................98
Hash: Element.Properties............................................................................................................................................99 Element Property: html...........................................................................................................................................99 Element Property: text...........................................................................................................................................100 Element Property: tag............................................................................................................................................102 Native: IFrame............................................................................................................................................................103 IFrame Method: constructor................................................................................................................................103 Native: Elements.........................................................................................................................................................105 Elements Method: constructor..............................................................................................................................105 Elements Method: filter.........................................................................................................................................106 Native: Element...........................................................................................................................................................107 Element Method: addEvent..................................................................................................................................107 Element Method: removeEvent............................................................................................................................108 Element Method: addEvents.................................................................................................................................108 Element Method: removeEvents...........................................................................................................................109 Element Method: fireEvent...................................................................................................................................110 Element Method: cloneEvents...............................................................................................................................111 Custom Events........................................................................................................................................................112 Native: Element...........................................................................................................................................................114 Element Method: setStyle......................................................................................................................................114 Element Method: getStyle......................................................................................................................................114 Element Method: setStyles....................................................................................................................................115 Element Method: getStyles....................................................................................................................................115 Native: Element...........................................................................................................................................................117 Element Method: scrollTo......................................................................................................................................117 Element Method: getSize.......................................................................................................................................117 Element Method: getScrollSize.............................................................................................................................118 Element Method: getScroll....................................................................................................................................118 Element Method: getPosition................................................................................................................................119 Element Method: getCoordinates.........................................................................................................................119 Native: Element...........................................................................................................................................................121 Element Property: getElements............................................................................................................................121 Element Property: getElement..............................................................................................................................122 Function: $E...........................................................................................................................................................122 Element Method: match........................................................................................................................................122 Selectors.Pseudo..........................................................................................................................................................124 Selector: enabled....................................................................................................................................................124 Selector: empty.......................................................................................................................................................124 Selector: contains...................................................................................................................................................124 Selector: nth-child..................................................................................................................................................125 Selector: even..........................................................................................................................................................126 Selector: odd...........................................................................................................................................................126 Selector: first...........................................................................................................................................................127 Selector: last............................................................................................................................................................127 Selector: only..........................................................................................................................................................127 Window Event: domready..........................................................................................................................................128 Object: JSON..............................................................................................................................................................129 JSON Method: encode...........................................................................................................................................129 JSON Method: decode...........................................................................................................................................129 Object: Cookie.............................................................................................................................................................131 Cookie Method: write............................................................................................................................................131 Cookie Method: read.............................................................................................................................................132 Cookie Method: dispose.........................................................................................................................................132 Class: Swiff..................................................................................................................................................................134 Swiff Function: remote..........................................................................................................................................135
Class: Fx.......................................................................................................................................................................136 Fx Method: constructor.........................................................................................................................................136 Fx Method: start.....................................................................................................................................................137 Fx Method: set........................................................................................................................................................137 Fx Method: cancel..................................................................................................................................................138 Fx Method: pause...................................................................................................................................................138 Fx Method: resume................................................................................................................................................138 Class: Fx.CSS..............................................................................................................................................................140 Class: Fx.Tween...........................................................................................................................................................141 Fx.Tween Method: constructor.............................................................................................................................141 Fx.Tween Method: set............................................................................................................................................141 Fx.Tween Method: start.........................................................................................................................................142 Hash: Element.Properties..........................................................................................................................................144 Element Property: tween.......................................................................................................................................144 Native: Element...........................................................................................................................................................146 Element Method: tween.........................................................................................................................................146 Element Method: fade............................................................................................................................................146 Element Method: highlight....................................................................................................................................147 Class: Fx.Morph..........................................................................................................................................................149 Fx.Morph Method: set...........................................................................................................................................150 Fx.Morph Method: start........................................................................................................................................150 Hash: Element.Properties..........................................................................................................................................152 Element Property: morph.....................................................................................................................................152 Native: Element...........................................................................................................................................................154 Element Method: morph.......................................................................................................................................154 Class: Fx.......................................................................................................................................................................155 Hash: Fx.Transitions...................................................................................................................................................156 Fx.Transitions Method: linear..............................................................................................................................156 Fx.Transitions Method: quad................................................................................................................................156 Fx.Transitions Method: cubic...............................................................................................................................156 Fx.Transitions Method: quart...............................................................................................................................156 Fx.Transitions Method: quint...............................................................................................................................156 Fx.Transitions Method: pow.................................................................................................................................156 Fx.Transitions Method: expo................................................................................................................................156 Fx.Transitions Method: circ..................................................................................................................................157 Fx.Transitions Method: sine..................................................................................................................................157 Fx.Transitions Method: back................................................................................................................................157 Fx.Transitions Method: bounce............................................................................................................................157 Fx.Transitions Method: elastic..............................................................................................................................157 Class: Fx.Transition....................................................................................................................................................158 Class: Request.............................................................................................................................................................159 Request Events: events..........................................................................................................................................159 Request Method: setHeader..................................................................................................................................161 Request Method: getHeader..................................................................................................................................161 Request Method: send............................................................................................................................................162 Request Method: cancel.........................................................................................................................................162 Hash: Element.Properties..........................................................................................................................................164 Element Property: send.........................................................................................................................................164 Native: Element...........................................................................................................................................................166 Element Method: send...........................................................................................................................................166 Class: Request.HTML................................................................................................................................................167 Hash: Element.Properties..........................................................................................................................................169 Element Property: load..........................................................................................................................................169 Native: Element...........................................................................................................................................................171
Element Method: load............................................................................................................................................171 Class: Request.JSON..................................................................................................................................................172 Class: Fx.Slide.............................................................................................................................................................173 Fx.Slide Method: slideIn........................................................................................................................................173 Fx.Slide Method: slideOut.....................................................................................................................................174 Fx.Slide Method: toggle.........................................................................................................................................174 Fx.Slide Method: hide............................................................................................................................................175 Fx.Slide Method: show...........................................................................................................................................176 Hash: Element.Properties..........................................................................................................................................177 Element Property: slide.........................................................................................................................................177 Native: Element...........................................................................................................................................................178 Element Method: slide...........................................................................................................................................178 Class: Fx.Scroll............................................................................................................................................................179 Fx.Scroll Method: constructor..............................................................................................................................179 Fx.Scroll Method: set.............................................................................................................................................180 Fx.Scroll Method: start..........................................................................................................................................180 Fx.Scroll Method: toTop........................................................................................................................................181 Fx.Scroll Method: toBottom..................................................................................................................................181 Fx.Scroll Method: toLeft.......................................................................................................................................182 Fx.Scroll Method: toRight.....................................................................................................................................182 Fx.Scroll Method: toElement................................................................................................................................182 Class: Fx.Elements......................................................................................................................................................184 Fx.Elements Method: set.......................................................................................................................................184 Fx.Elements Method: start....................................................................................................................................185 Class: Drag..................................................................................................................................................................186 Drag Method: constructor.....................................................................................................................................186 Drag Method: attach..............................................................................................................................................187 Drag Method: detach.............................................................................................................................................188 Drag Method: stop.................................................................................................................................................188 Native: Element...........................................................................................................................................................189 Element Method: makeResizable.........................................................................................................................189 Class: Drag.Move........................................................................................................................................................190 Drag.Move Method: constructor..........................................................................................................................190 Drag.Move Method: stop.......................................................................................................................................191 Native: Element...........................................................................................................................................................193 Element Method: makeDraggable........................................................................................................................193 Class: Color.................................................................................................................................................................194 Color Method: mix.................................................................................................................................................195 Color Method: invert.............................................................................................................................................195 Color Method: setHue............................................................................................................................................195 Color Method: setSaturation.................................................................................................................................196 Color Method: setBrightness.................................................................................................................................196 Function: $RGB.....................................................................................................................................................197 Function: $HSB......................................................................................................................................................197 Native: Array...............................................................................................................................................................199 Array Method: rgbToHsb.....................................................................................................................................199 Array Method: hsbToRgb.....................................................................................................................................199 Class: Group................................................................................................................................................................200 Group Method: addEvent.....................................................................................................................................200 Class: Hash.Cookie.....................................................................................................................................................202 Hash.Cookie Method: save....................................................................................................................................203 Hash.Cookie Method: load....................................................................................................................................203 Class: Sortables...........................................................................................................................................................205 Sortables Method: attach......................................................................................................................................206
Sortables Method: detach......................................................................................................................................206 Sortables Method: detach......................................................................................................................................206 Sortables Method: addItems.................................................................................................................................206 Sortables Method: removeItems...........................................................................................................................207 Sortables Method: addLists..................................................................................................................................208 Sortables Method: removeLists............................................................................................................................209 Sortables Method: serialize...................................................................................................................................209 Class: Tips....................................................................................................................................................................211 Tips Method: constructor......................................................................................................................................211 Tips Event: onShow...............................................................................................................................................212 Tips Event: onHide.................................................................................................................................................212 Tips Method: attach...............................................................................................................................................212 Tips Method: detach..............................................................................................................................................213 Tips HTML Structure............................................................................................................................................214 Tips with storage....................................................................................................................................................214 Class: SmoothScroll....................................................................................................................................................215 Class: Slider.................................................................................................................................................................216 Slider Event: onChange.........................................................................................................................................216 Slider Event: onComplete......................................................................................................................................217 Slider Event: onTick..............................................................................................................................................217 Slider Method: set..................................................................................................................................................218 Class: Scroller..............................................................................................................................................................219 Scroller Method: start............................................................................................................................................220 Scroller Method: stop.............................................................................................................................................220 Hash: Assets.................................................................................................................................................................221 Assets Method: javascript.....................................................................................................................................221 Assets Method: css..................................................................................................................................................221 Assets Method: image............................................................................................................................................222 Assets Method: images...........................................................................................................................................222 Options:...................................................................................................................................................................223 Class: Accordion..........................................................................................................................................................224 Events:.....................................................................................................................................................................225 Accordion Method: addSection............................................................................................................................225 Accordion Method: display...................................................................................................................................226
Core
Core contains an handful of common sense functions used in MooTools. It also contains some basic Hash and Array methods.
Function: $chk
Checks to see if a value exists or is 0. Useful for allowing 0.
Syntax:
$chk(item);
Arguments:
1. item - (mixed) The item to inspect.
Returns:
(boolean) If the object passed in exists or is 0, returns true. Otherwise, returns false.
Example:
function myFunction(arg){ if($chk(arg)) alert('The object exists or is 0.'); else alert('The object is either null, undefined, false, or ""'); }
Function: $clear
Clears a Timeout or an Interval. Useful when working with Function:delay and Function:periodical.
Syntax:
$clear(timer);
Arguments:
1. timer - (number) The identifier of the setInterval (periodical) or setTimeout (delay) to clear.
Returns:
Example:
var myTimer = myFunction.delay(5000); //Waits 5 seconds then executes myFunction. myTimer = $clear(myTimer); //Cancels myFunction.
See also:
Function:delay Function:periodical
Function: $defined
Checks to see if a value is defined.
Syntax:
$defined(obj);
Arguments:
1. obj - (mixed) The object to inspect.
Returns:
(boolean) If the object passed is not null or undefined, returns true. Otherwise, returns false.
Example:
function myFunction(arg){ if($defined(arg)) alert('The object is defined.'); else alert('The object is null or undefined.'); }
Function: $arguments
Creates a function which returns the passed argument according to the index (i) passed.
Syntax:
var argument = $arguments(i);
Arguments
1. i - (number) The index of the argument to return.
Returns
(function) The function that returns a certain argument from the function's arguments.
Example:
var secondArgument = $arguments(1); alert(secondArgument('a','b','c')); //Alerts "b".
Function: $empty
An empty function, that's it. Typically used for as a placeholder inside event methods of classes.
Syntax:
var emptyFn = $empty;
Example:
var myFunc = $empty;
Function: $lambda
Creates an empty function which does nothing but return the value passed.
Syntax:
var returnTrue = $lambda(true);
Arguments
1. value - (mixed) The value for the created function to return.
Returns
Example:
myLink.addEvent('click', $lambda(false)); //Prevents a link Element from being clickable.
Function: $extend
Copies all the properties from the second object passed in to the first object passed in. In myObject.extend = $extend, the first parameter will become myObject, and the extend function will only need one parameter.
Syntax:
$extend(original, extended);
Arguments:
1. original - (object) The object to be extended. 2. extended - (object) The object whose properties will be copied to src.
Returns:
Examples:
Normal Extension:
var firstObj = { 'name': 'John', 'lastName': 'Doe' }; var secondObj = { 'age': '20', 'sex': 'male', 'lastName': 'Dorian' }; $extend(firstObj, secondObj); //firstObj is now: { 'name': 'John', 'lastName': 'Dorian', 'age': '20', 'sex': 'male' };
Function: $merge
Merges any number of objects recursively without referencing them or their sub-objects.
Syntax:
var merged = $merge(obj1, obj2[, obj3[, ...]]);
Arguments:
1. (objects) Any number of objects.
Returns:
(object) The object that is created as a result of merging all the objects passed in.
Examples:
var var var var obj1 = {a: 0, b: 1}; obj2 = {c: 2, d: 3}; obj3 = {a: 4, d: 5}; merged = $merge(obj1, obj2, obj3); //returns {a: 4, b: 1, c: 2, d: 5}, (obj1, obj2, and obj3 are unaltered)
var nestedObj1 = {a: {b: 1, c: 1}}; var nestedObj2 = {a: {b: 2}}; var nested = $merge(nestedObj1, nestedObj2); //returns: {a: {b: 2, c: 1}}
Function: $each
Used to iterate through iterables that are not regular arrays, such as built in getElementsByTagName calls, arguments of a function, or an object.
Syntax:
$each(iterable, fn[, bind]);
Arguments:
1. iterable - (object or array) The object or array to iterate through. 2. fn - (function) The function to test for each element. 3. bind - (object, optional) The object to use as 'this' within the function. For more information see Function:bind. Argument: fn
Syntax:
fn(item, index, object)
Arguments:
1. item - (mixed) The current item in the array. 2. index - (number) The current item's index in the array. In the case of an object, it is passed the key of that item rather than the index. 3. object - (mixed) The actual array/object.
Examples:
Array Example:
$each(['Sun','Mon','Tue'], function(day, index){ alert('name:' + day + ', index: ' + index); }); //Alerts "name: Sun, index: 0", "name: Mon, index: 1", etc.
Object Example:
//Alerts "The first day of the week is Sunday", "The second day of the week is Monday", etc: $each({first: "Sunday", second: "Monday", third: "Tuesday"}, function(value, key){ alert("The " + key + " day of the week is " + value); });
Function: $pick
Returns the first defined argument passed in, or null.
Syntax:
var picked = $pick(var1[, var2[, var3[, ...]]]);
Arguments:
Returns:
(mixed) The first variable that is defined. (false) If all variables passed in are null or undefined, returns null.
Example:
function say(infoMessage, errorMessage){ alert($pick(errorMessage, infoMessage, 'There was no message supplied.')); } say(); //Alerts "There was no message supplied." say("This is an info message."); //Alerts "This is an info message." say("This message will be ignored.", "This is the error message."); //Alerts "This is the error message."
Function: $random
Returns a random integer between the two passed in values.
Syntax:
var random = $random(min, max);
Arguments:
1. min - (number) The minimum value (inclusive). 2. max - (number) The maximum value (inclusive).
Returns:
Example:
alert($random(5, 20)); //Alerts a random number between 5 and 20.
Function: $splat
Converts the argument passed in to an array if it is defined and not already an array.
Syntax:
var splatted = $splat(obj);
Arguments:
1. obj - (mixed) Any type of variable.
Returns:
(array) If the variable passed in is an array, returns the array. Otherwise, returns an array with the only element being the variable passed in.
Example:
$splat('hello'); //Returns ['hello']. $splat(['a', 'b', 'c']); //Returns ['a', 'b', 'c'].
Function: $time
Returns the current time as a timestamp.
Syntax:
var time = $time();
Returns:
Function: $try
Tries to execute a number of functions. Returns immediately the return value of the first non-failed function without executing successive functions, or null.
Syntax:
$try(fn[, fn, fn, fn, ...]);
Arguments:
Returns:
(mixed) Standard return of the called function. (null) null if all the passed functions fail.
Examples:
var result = $try(function(){ return some.made.up.object; }, function(){ return jibberish.that.doesnt.exists; }, function(){ return false; }); //result is false var failure, success; $try(function(){ some.made.up.object = 'something'; success = true; }, function(){ failure = true; }); if (success) alert('yey!');
Function: $type
Returns the type of object that matches the element passed in.
Syntax:
$type(obj);
Arguments:
1. obj - (object) The object to inspect.
Returns:
'element' - (string) If object is a DOM element node. 'textnode' - (string) If object is a DOM text node. 'whitespace' - (string) If object is a DOM whitespace node. 'arguments' - (string) If object is an arguments object. 'array' - (string) If object is an array. 'object' - (string) If object is an object. 'string' - (string) If object is a string. 'number' - (string) If object is a number. 'date' - (string) If object is a date. 'boolean' - (string) If object is a boolean. 'function' - (string) If object is a function. 'regexp' - (string) If object is a regular expression. 'class' - (string) If object is a Class (created with new Class, or the extend of another class). 'collection' - (string) If object is a native htmlelements collection, such as childNodes, getElementsByTagName, etc. 'window' - (string) If object is the window object. 'document' - (string) If object is the document object. false - (boolean) If object is undefined, null, NaN or none of the above.
Example:
var myString = 'hello'; $type(myString); //Returns "string".
Hash: Browser
Some browser properties are attached to the Browser Object for browser and platform detection.
Features:
Browser.Features.xpath - (boolean) True if the browser supports DOM queries using XPath. Browser.Features.xhr - (boolean) True if the browser supports native XMLHTTP object.
Engine:
Browser.Engine.trident - (boolean) True if the current browser is Internet Explorer (any). Browser.Engine.trident4 - (boolean) True if the current browser is Internet Explorer 6. Browser.Engine.trident5 - (boolean) True if the current browser is Internet Explorer 7. Browser.Engine.gecko - (boolean) True if the current browser is Mozilla/Gecko. Browser.Engine.webkit - (boolean) True if the current browser is Safari/Konqueror. Browser.Engine.webkit419 - (boolean) True if the current browser is Safari2/WebKit before version 419. Browser.Engine.webkit420 - (boolean) True if the current browser is Safari3 (WebKit SVN Build)/WebKit after version 419. Browser.Engine.presto - (boolean) True if the current browser is Opera. Browser.Engine.presto925 - (boolean) True if the current browser is Opera before or equal version 9.25. Browser.Engine.presto950 - (boolean) True if the current browser is Opera major or equal version 9.50. Browser.Engine.name - (string) The name of the engine. Browser.Plugins.Flash.version - (number) The major version of the flash plugin installed. Browser.Plugins.Flash.build - (number) The build version of the flash plugin installed.
Platform:
Browser.Platform.mac - (boolean) True if the platform is Mac. Browser.Platform.win - (boolean) True if the platform is Windows. Browser.Platform.linux - (boolean) True if the platform is Linux. Browser.Platform.ipod - (boolean) True if the platform is an ipod touch / iphone. Browser.Platform.other - (boolean) True if the platform is neither Mac, Windows or Linux. Browser.Platform.name - (string) The name of the platform.
Notes:
10
Native: Array
A collection of Array methods.
See Also:
MDC Array
Syntax:
myArray.each(fn[, bind]);
Arguments:
1. fn - (function) The function which should be executed on each item in the array. This function is passed the item and its index in the array. 2. bind - (object, optional) The object to be used as 'this' in the function. For more information see Function:bind. Argument: fn
Syntax
fn(item, index, array)
Arguments:
1. item - (mixed) The current item in the array. 2. index - (number) The current item's index in the array. 3. array - (array) The actual array.
Examples:
//Alerts "0 = apple", "1 = banana", and so on: ['apple', 'banana', 'lemon'].each(function(item, index){ alert(index + " = " + item); }); //The optional second argument for binding isn't used here.
See Also:
MDC Array:forEach
11
Notes:
This method is only available for browsers without native MDC Array:forEach support.
Syntax:
var allPassed = myArray.every(fn[, bind]);
Arguments:
1. fn - (function) The function to test for each element. 2. bind - (object, optional) The object to use as 'this' in the function. For more information see Function:bind. Argument: fn
Syntax:
fn(item, index, array)
Arguments:
1. item - (mixed) The current item in the array. 2. index - (number) The current item's index in the array. 3. array - (array) The actual array.
Returns:
(boolean) If every element in the array satisfies the provided testing function, returns true. Otherwise, returns false.
Examples:
var areAllBigEnough = [10, 4, 25, 100].every(function(item, index){ return item > 20; }); //areAllBigEnough = false
See Also:
MDC Array:every
12
Syntax:
var filteredArray = myArray.filter(fn[, bind]);
Arguments:
1. fn - (function) The function to test each element of the array. This function is passed the item and its index in the array. 2. bind - (object, optional) The object to use as 'this' in the function. For more information see Function:bind. Argument: fn
Syntax:
fn(item, index, array)
Arguments:
1. item - (mixed) The current item in the array. 2. index - (number) The current item's index in the array. 3. array - (array) The actual array.
Returns:
Examples:
var biggerThanTwenty = [10, 3, 25, 100].filter(function(item, index){ return item > 20; }); //biggerThanTwenty = [25, 100]
See Also:
MDC Array:filter
13
Syntax:
var cleanedArray = myArray.clean();
Returns:
Examples:
var cleanedArray = [0, 3, null, false, true, "foo", ""].clean(); //cleanedArray = [3, true, "foo"]
Syntax:
var index = myArray.indexOf(item[, from]);
Returns:
(number) The index of the first element within the array equal to the specified value. If not found, returns -1.
Arguments:
1. item - (object) The item to search for in the array. 2. from - (number, optional: defaults to 0) The index of the array at which to begin the search.
Examples:
['apple', 'lemon', 'banana'].indexOf('lemon'); //returns 1 ['apple', 'lemon'].indexOf('banana'); //returns -1
See Also:
MDC Array:indexOf
14
Syntax:
var mappedArray = myArray.map(fn[, bind]);
Arguments:
1. fn - (function) The function to produce an element of the new Array from an element of the current one. 2. bind - (object, optional) The object to use as 'this' in the function. For more information see Function:bind. Argument: fn
Syntax:
fn(item, index, array)
Arguments:
1. item - (mixed) The current item in the array. 2. index - (number) The current item's index in the array. 3. array - (array) The actual array.
Returns:
Examples:
var timesTwo = [1, 2, 3].map(function(item, index){ return item * 2; }); //timesTwo = [2, 4, 6];
See Also:
MDC Array:map
Syntax:
var somePassed = myArray.some(fn[, bind]);
15
Returns:
(boolean) If at least one element in the array satisfies the provided testing function returns true. Otherwise, returns false.
Arguments:
1. fn - (function) The function to test for each element. This function is passed the item and its index in the array. 2. bind - (object, optional) The object to use as 'this' in the function. For more information see Function:bind. Argument: fn
Syntax:
fn(item, index, array)
Arguments:
1. item - (mixed) The current item in the array. 2. index - (number) The current item's index in the array. 3. array - (array) The actual array.
Examples:
var isAnyBigEnough = [10, 4, 25, 100].some(function(item, index){ return item > 20; }); //isAnyBigEnough = true
See Also:
MDC Array:some
Syntax:
var associated = myArray.associate(obj);
Arguments:
1. obj - (array) Its items will be used as the keys of the object that will be created.
16
Returns:
Examples:
var animals = ['Cow', 'Pig', 'Dog', 'Cat']; var sounds = ['Moo', 'Oink', 'Woof', 'Miao']; sounds.associate(animals); //returns {'Cow': 'Moo', 'Pig': 'Oink', 'Dog': 'Woof', 'Cat': 'Miao'}
Syntax:
var result = Array.link(array, object);
Arguments:
1. object - (object) An object containing key / function pairs must be passed to be used as a template for associating values with the different keys.
Returns:
Examples:
var el = document.createElement('div'); var arr2 = [100, 'Hello', {foo: 'bar'}, el, false]; arr2.link({myNumber: Number.type, myElement: Element.type, myObject: Object.type, myString: String.type, myBoolean: $defined}); //returns {myNumber: 100, myElement: el, myObject: {foo: 'bar'}, myString: 'Hello', myBoolean: false}
Syntax:
var inArray = myArray.contains(item[, from]);
17
Arguments:
1. item - (object) The item to search for in the array. 2. from - (number, optional: defaults to 0) The index of the array at which to begin the search.
Returns:
(boolean) If the array contains the item specified, returns true. Otherwise, returns false.
Examples:
["a","b","c"].contains("a"); //returns true ["a","b","c"].contains("d"); //returns false
See Also:
MDC Array:indexOf
Syntax:
myArray.extend(array);
Arguments:
1. array - (array) The array whose items should be extended into this array.
Returns:
Examples:
var animals = ['Cow', 'Pig', 'Dog']; animals.extend(['Cat', 'Dog']); //animals = ['Cow', 'Pig', 'Dog', 'Cat', 'Dog'];
Syntax:
myArray.getLast();
18
Returns:
(mixed) The last item in this array. (false) If this array is empty, returns null.
Examples:
['Cow', 'Pig', 'Dog', 'Cat'].getLast(); //returns 'Cat'
Syntax:
myArray.getRandom();
Returns:
(mixed) A random item from this array. If this array is empty, returns null.
Examples:
['Cow', 'Pig', 'Dog', 'Cat'].getRandom(); //returns one of the items
Syntax:
myArray.include(item);
Arguments:
1. item - (object) The item that should be added to this array.
Returns:
19
Examples:
['Cow', 'Pig', 'Dog'].include('Cat'); //returns ['Cow', 'Pig', 'Dog', 'Cat'] ['Cow', 'Pig', 'Dog'].include('Dog'); //returns ['Cow', 'Pig', 'Dog']
Syntax:
myArray.combine(array);
Arguments:
1. array - (array) The array whose items should be combined into this array.
Returns:
Examples:
var animals = ['Cow', 'Pig', 'Dog']; animals.combine(['Cat', 'Dog']); //animals = ['Cow', 'Pig', 'Dog', 'Cat'];
Syntax:
myArray.erase(item);
Arguments:
1. item - (object) The item to search for in the array.
Returns:
20
Examples:
['Cow', 'Pig', 'Dog', 'Cat', 'Dog'].erase('Dog') //returns ['Cow', 'Pig', 'Cat'] ['Cow', 'Pig', 'Dog'].erase('Cat') //returns ['Cow', 'Pig', 'Dog']
Syntax:
myArray.empty();
Returns:
Examples:
var myArray = ['old', 'data']; myArray.empty(); //myArray is now []
Syntax:
myArray.flatten();
Returns:
Examples:
var myArray = [1,2,3,[4,5, [6,7]], [[[8]]]]; var newArray = myArray.flatten(); //newArray is [1,2,3,4,5,6,7,8]
21
Syntax:
myArray.rgbToHex([array]);
Arguments:
1. array - (boolean, optional) If true is passed, will output an array (eg. ['ff','33','00']) instead of a string (eg. "#ff3300").
Returns:
(string) A string representing the color in hexadecimal, or 'transparent' string if the fourth value of rgba in the input array is 0 (rgba). (array) If the array flag is set, an array will be returned instead.
Examples:
[17,34,51].rgbToHex(); //returns "#112233" [17,34,51].rgbToHex(true); //returns ['11','22','33'] [17,34,51,0].rgbToHex(); //returns "transparent"
See Also:
String:rgbToHex
22
Utility Functions
Function: $A
Creates a copy of an Array. Useful for applying the Array prototypes to iterable objects such as a DOM Node collection or the arguments object.
Syntax:
var copiedArray = $A(iterable);
Arguments:
1. iterable - (array) The iterable to copy.
Returns:
Examples:
Apply Array to arguments:
function myFunction(){ $A(arguments).each(function(argument, index){ alert(argument); }); }; myFunction("One", "Two", "Three"); //Alerts "One", then "Two", then "Three".
Copy an Array:
var anArray = [0, 1, 2, 3, 4]; var copiedArray = $A(anArray); //Returns [0, 1, 2, 3, 4].
23
Native: Function
Function Methods.
See Also:
MDC Function
Syntax:
var createdFunction = myFunction.create([options]);
Arguments:
1. [options] - (object, optional) The options from which the function will be created. If options is not provided, then creates a copy of the function. Options:
bind - (object: defaults to this function) The object that the "this" of the function will refer to. event - (mixed: defaults to false) If set to true, the function will act as an event listener and receive an event as its first argument. If set to a class name, the function will receive a new instance of this class (with the event passed as argument's constructor) as first argument. arguments - (mixed: defaults to standard arguments) A single argument or an array of arguments that will be passed as arguments to the function. If both the event and arguments options are set, the event is passed as first argument and the arguments array will follow. delay - (number: defaults to no delay) If set, the returned function will delay the actual execution by this amount of milliseconds and return a timer handle when called. periodical - (number: defaults to no periodical execution) If set, the returned function will periodically perform the actual execution with this specified interval and return a timer handle when called. attempt - (boolean: false) If set to true, the returned function will try to execute and return either the results or null on error.
Returns:
(function) The function that was created as a result of the options passed in.
24
Example:
var myFunction = function(){ alert("I'm a function. :)"); }; var mySimpleFunction = myFunction.create(); //Just a simple copy. var myAdvancedFunction = myFunction.create({ //When called, this function will attempt. arguments: [0,1,2,3], attempt: true, delay: 1000, bind: myElement });
Syntax:
var newFunction = myFunction.pass([args[, bind]]);
Arguments:
1. args - (mixed, optional) The arguments to pass to the function (must be an array if passing more than one argument). 2. bind - (object, optional) The object that the "this" of the function will refer to.
Returns:
Example:
var myFunction = function(){ var result = 'Passed: '; for (var i = 0, l = arguments.length; i < l; i++){ result += (arguments[i] + ' '); } return result; } var myHello = myFunction.pass('hello'); var myItems = myFunction.pass(['peach', 'apple', 'orange']); //Later in the code, the functions can be executed: alert(myHello()); //Passes "hello" to myFunction. alert(myItems()); //Passes the array of items to myFunction.
25
Syntax:
var result = myFunction.attempt([args[, bind]]);
Arguments:
1. args - (mixed, optional) The arguments to pass to the function (must be an array if passing more than one argument). 2. bind - (object, optional) The object that the "this" of the function will refer to.
Returns:
Example:
var myObject = { 'cow': 'moo!' }; var myFunction = function(){ for (var i = 0; i < arguments.length; i++){ if(!this[arguments[i]]) throw('doh!'); } }; var result = myFunction.attempt(['pig', 'cow'], myObject); //result = false
Syntax:
myFunction.bind([bind[, args[, evt]]]);
Arguments:
1. bind - (object, optional) The object that the "this" of the function will refer to. 2. args - (mixed, optional) The arguments to pass to the function (must be an array if passing more than one argument).
Returns:
26
Example:
function myFunction(){ //Note that 'this' here refers to window, not an element. //The function must be bound to the element we want to manipulate. this.setStyle('color', 'red'); }; var myBoundFunction = myFunction.bind(myElement); myBoundFunction(); //This will make myElement's text red.
Syntax:
myFunction.bindWithEvent([bind[, args[, evt]]]);
Arguments:
1. bind - (object, optional) The object that the "this" of the function will refer to. 2. args - (mixed, optional) The arguments to pass to the function (must be an array if passing more than one argument).
Returns:
Example:
function myFunction(e, add){ //Note that 'this' here refers to window, not an element. //We'll need to bind this function to the element we want to alter. this.setStyle('top', e.client.x + add); }; $(myElement).addEvent('click', myFunction.bindWithEvent(myElement, 100); //When clicked, the element will move to the position of the mouse + 100.
Syntax:
var timeoutID = myFunction.delay([delay[, bind[, args]]]);
27
Arguments:
1. delay - (number, optional) The duration to wait (in milliseconds). 2. bind - (object, optional) The object that the "this" of the function will refer to. 3. args - (mixed, optional) The arguments passed (must be an array if the arguments are greater than one).
Returns:
Example:
var myFunction = function(){ alert('moo! Element id is: ' + this.id); }; //Wait 50 milliseconds, then call myFunction and bind myElement to it. myFunction.delay(50, myElement); //Alerts: 'moo! Element id is: ... ' //An anonymous function which waits a second and then alerts. (function(){ alert('one second later...'); }).delay(1000);
See Also:
Syntax:
var intervalID = myFunction.periodical([period[, bind[, args]]]);
Arguments:
1. period - (number, optional) The duration of the intervals between executions. 2. bind - (object, optional) The object that the "this" of the function will refer to. 3. args - (mixed, optional) The arguments passed (must be an array if the arguments are greater than one).
Returns:
Example:
var Site = { counter: 0 }; var addCount = function(){ this.counter++; }; addCount.periodical(1000, Site); //Will add the number of seconds at the Site.
28
See Also:
Syntax:
var myFunctionResult = myFunction.run(args[, bind]);
Arguments:
1. args - (mixed) An argument, or array of arguments to run the function with. 2. bind - (object, optional) The object that the "this" of the function will refer to.
Returns:
Examples:
Simple Run:
var myFn = function(a, b, c){ return a + b + c; } var myArgs = [1,2,3]; myFn.run(args); //Returns: 6
29
Native: Number
A collection of the Number Object methods.
See Also:
MDC Number
Notes:
Every Math method is mirrored in the Number object, both as prototype and generic.
Syntax:
myNumber.limit(min, max);
Arguments:
1. min - (number) The minimum possible value. 2. max - (number) The maximum possible value.
Returns:
Examples:
(12).limit(2, 6.5); //Returns: 6.5 (-4).limit(2, 6.5); //Returns: 2 (4.3).limit(2, 6.5); //Returns: 4.3
Syntax:
myNumber.round([precision]);
Arguments:
1. precision - (number, optional: defaults to 0) The number of digits after the decimal place. 30
Returns:
Notes:
Examples:
(12.45).round() //Returns: 12 (12.45).round(1) //Returns: 12.5 (12.45).round(-1) //Returns: 10
Syntax:
myNumber.times(fn[, bind]);
Arguments:
1. fn - (function) The function which should be executed on each iteration of the loop. This function is passed the current iteration's index. 2. bind - (object, optional) The object to use as 'this' in the function. For more information see Function:bind.
Examples:
(4).times(alert); //Alerts "0", then "1", then "2", then "3".
Syntax:
myNumber.toFloat();
Returns:
31
Examples:
(111).toFloat(); //returns 111 (111.1).toFloat(); //returns 111.1
Syntax:
myNumber.toInt([base]);
Arguments:
1. base - (number, optional: defaults to 10) The base to use.
Returns:
Examples:
(111).toInt(); //returns 111 (111.1).toInt(); //returns 111 (111).toInt(2); //returns 7
32
Native: String
A collection of the String Object prototype methods.
See Also:
MDC String
Syntax:
myString.test(regex[,params]);
Arguments:
1. regex - (mixed) The string or regular expression you want to match the string with. 2. params - (string, optional) If first parameter is a string, any parameters you want to pass to the regular expression ('g' has no effect).
Returns:
(boolean) true, if a match for the regular expression is found in this string. (boolean) false if is not found
Examples:
"I like cookies".test("cookie"); //returns true "I like cookies".test("COOKIE", "i"); //returns true (ignore case) "I like cookies".test("cake"); //returns false
See Also:
Syntax:
myString.contains(string[, separator]);
33
Arguments:
1. string - (string) The string to search for. 2. separator - (string, optional) The string that separates the values in this string (eg. Element classNames are separated by a ' ').
Returns:
(boolean) true if the string is contained in this string (boolean) false if not.
Examples:
'a bc'.contains('bc'); //returns true 'a b c'.contains('c', ' '); //returns true 'a bc'.contains('b', ' '); //returns false
Syntax:
myString.trim();
Returns:
Examples:
" i like cookies ".trim(); //"i like cookies"
Syntax:
myString.clean();
Returns:
34
Examples:
"i like cookies \n\n".clean(); //returns "i like cookies"
Syntax:
myString.camelCase();
Returns:
Examples:
"I-like-cookies".camelCase(); //returns "ILikeCookies"
Syntax:
myString.hyphenate();
Returns:
Examples:
"ILikeCookies".hyphenate(); //returns "I-like-cookies"
35
Syntax:
myString.capitalize();
Returns:
Examples:
"i like cookies".capitalize(); //returns "I Like Cookies"
Syntax:
myString.escapeRegExp();
Returns:
Examples:
'animals.sheep[1]'.escapeRegExp(); //returns 'animals\.sheep\[1\]'
Syntax:
myString.toInt([base]);
Arguments:
1. base - (number, optional) The base to use (defaults to 10).
Returns:
(number) The number. (false) If the string is not numeric, returns NaN. 36
Examples:
"4em".toInt(); //returns 4 "10px".toInt(); //returns 10
See Also:
MDC parseInt
Syntax:
myString.toFloat();
Returns:
(number) The float. (false) If the string is not numeric, returns NaN.
Examples:
"95.25%".toFloat(); //returns 95.25 "10.848".toFloat(); //returns 10.848
See Also:
MDC parseFloat
Syntax:
myString.hexToRgb([array]);
Arguments:
1. array - (boolean, optional) If true is passed, will output an array (eg. ['ff','33','00']) instead of a string (eg. "#ff3300").
37
Returns:
(string) A string representing the color in RGB. (array) If the array flag is set, an array will be returned instead.
Examples:
"#123".hexToRgb(); //returns "rgb(17,34,51)" "112233".hexToRgb(); //returns "rgb(17,34,51)" "#112233".hexToRgb(true); //returns [17,34,51]
Syntax:
myString.rgbToHex([array]);
Arguments:
1. array - (boolean, optional) If true is passed, will output an array (eg. ['ff','33','00']) instead of a string (eg. "#ff3300").
Returns:
(string) A string representing the color in hexadecimal, or transparent if the fourth value of rgba in the input string is 0. (array) If the array flag is set, an array will be returned instead.
Examples:
"rgb(17,34,51)".rgbToHex(); //returns "#112233" "rgb(17,34,51)".rgbToHex(true); //returns ['11','22','33'] "rgba(17,34,51,0)".rgbToHex(); //returns "transparent"
See Also:
Array:rgbToHex
38
Syntax:
myString.stripScripts([evaluate]);
Arguments:
1. evaluate - (boolean, optional) If true is passed, the scripts within the String will be evaluated.
Returns:
Examples:
var myString = "<script>alert('Hello')</script>Hello, World."; myString.stripScripts(); //Returns "Hello, World." myString.stripScripts(true); //Alerts "Hello", then returns "Hello, World."
Syntax:
myString.substitute(object[, regexp]);
Arguments:
1. object - (mixed) The key/value pairs used to substitute a string. 2. regexp - (regexp, optional) The regexp pattern to be used in the string keywords, with global flag. Defaults to /\?{([^}]+)}/g .
Returns:
Examples:
var myString = "{subject} is {property_1} and {property_2}."; var myObject = {subject: 'Jack Bauer', property_1: 'our lord', property_2: 'savior'}; myString.substitute(myObject); //Jack Bauer is our lord and savior
39
Native: Hash
A custom Object ({}) implementation which does not account for prototypes when setting, getting, or iterating. Useful because in JavaScript, we cannot use Object.prototype. Instead, we can use Hash.prototype!
Arguments:
1. object - (mixed) A hash or object to implement.
Returns:
Examples:
var myHash = new Hash({ aProperty: true, aMethod: function(){ return true; } }); alert(myHash.has('aMethod')); //Returns true.
Syntax:
myHash.each(fn[, bind]);
Arguments:
1. fn - (function) The function which should be executed on each item in the array. This function is passed the item and its index in the array. 2. bind - (object, optional) The object to use as 'this' in the function. For more information, see [Function:bind][].
40
Argument: fn
Syntax:
fn(value, key, hash)
Arguments:
1. value - (mixed) The current value in the hash. 2. key - (string) The current value's key in the hash. 3. hash - (hash) The actual hash.
Examples:
var hash = new Hash({first: "Sunday", second: "Monday", third: "Tuesday"}); hash.each(function(value, key){ alert("the " + key + " day of the week is " + value); }); //Alerts "the first day of the week is Sunday", "the second day of the week is Monday", etc.
Syntax:
var inHash = myHash.has(item);
Arguments:
1. key - (string) The key to search for in the Hash.
Returns:
(boolean) If the Hash has a defined value for the specified key, returns true. Otherwise, returns false.
Examples:
var hash = new Hash({'a': 'one', 'b': 'two', 'c': 'three'}); hash.has('a'); //returns true hash.has('d'); //returns false
Notes:
Testing for a Hash prototype will never return true. Only testing the actual properties of the Hash will return true.
41
Syntax:
var key = myHash.keyOf(item);
Arguments:
1. item - (mixed) The item to search for in the Hash.
Returns:
(string) If the Hash has a the specified item in it, returns the key of that item. (boolean) Otherwise, returns false.
Examples:
var hash = new Hash({'a': 'one', 'b': 'two', 'c': 3}); hash.keyOf('two'); //returns 'b' hash.keyOf(3); //returns 'c' hash.keyOf('four') //returns false
Notes:
Testing for a Hash prototype will never return its key. Only the actual properties of the Hash will return their associated key.
Syntax:
var inHash = myHash.hasValue(value);
Arguments:
1. value - (mixed) The value to search for in the Hash.
Returns:
(boolean) If the Hash has the passed in value in any of the keys, returns true. Otherwise, returns false.
42
Examples:
var hash = new Hash({'a': 'one', 'b': 'two', 'c': 'three'}); hash.hasValue('one'); //returns true hash.hasValue('four'); //returns false
Syntax:
myHash.extend(properties);
Arguments:
1. properties - (object) The object whose items should be extended into this Hash
Returns:
Examples:
var hash = new Hash({ 'name': 'John', 'lastName': 'Doe' }); var properties = { 'age': '20', 'sex': 'male', 'lastName': 'Dorian' }; hash.extend(properties); //hash now holds an object containing: { 'name': 'John', 'lastName': 'Dorian', 'age': '20', 'sex': 'male' };
Syntax:
myHash.combine(properties);
43
Arguments:
1. properties - (object) The object whose items should be combined into this Hash.
Returns:
Examples:
var hash = new Hash({ 'name': 'John', 'lastName': 'Doe' }); var properties = { 'name': 'Jane' 'age': '20', 'sex': 'male', 'lastName': 'Dorian' }; hash.combine(properties); //hash now holds an object containing: { 'name': 'John', 'lastName': 'Doe', 'age': '20', 'sex': 'male' };
Syntax:
myHash.erase(key);
Arguments:
1. key - (string) The key to search for in the Hash.
Returns:
(hash) This Hash with the specified key and its value removed.
Examples:
var hash = new Hash({ 'name': 'John', 'lastName': 'Doe' }); hash.erase('lastName'); //hash now holds an object containing: { 'name': 'John' };
44
Syntax:
myHash.get(key);
Arguments:
1. key - (string) The key to retrieve in the Hash.
Returns:
(mixed) Returns the value that corresponds to the key if found. (false) null if the key doesn't exist
Examples:
var hash = new Hash({ 'name': 'John', 'lastName': 'Doe' }); hash.get('name'); //returns 'John'
Syntax:
myHash.set(key, value);
Arguments:
1. key - (string) The key to insert or modify in the Hash. 2. value - (mixed) The value to associate with the specified key in the Hash.
Returns:
(hash) This Hash with the specified key set to the specified value.
45
Examples:
var hash = new Hash({ 'name': 'John', 'lastName': 'Doe' }); hash.set('name', 'Michelle'); //hash.name is now 'Michelle'
Syntax:
myHash.empty();
Examples:
var hash = new Hash({ 'name': 'John', 'lastName': 'Doe' }); hash.empty(); //hash now holds an empty object: {}
Syntax:
myHash.include(key, value);
Arguments:
1. key - (string) The key to insert into the Hash. 2. value - (mixed) The value to associate with the specified key in the Hash.
Returns:
(hash) This Hash with the specified key included if it did not previously exist.
46
Examples:
var hash = new Hash({ 'name': 'John', 'lastName': 'Doe' }); hash.include('name', 'Michelle'); //hash is unchanged hash.include('age', 25); //hash.age is now 25
Syntax:
var mappedHash = myHash.map(fn[, bind]);
Arguments:
1. fn - (function) The function to produce an element of the new Array from an element of the current one. 2. bind - (object, optional) The object to use as 'this' in the function. For more information see [Function:bind][]. Argument: fn
Syntax:
fn(value, key, hash)
Arguments:
1. value - (mixed) The current value in the hash. 2. key - (string) The current value's key in the hash. 3. hash - (hash) The actual hash.
Returns:
Examples:
var timesTwo = new Hash({a: 1, b: 2, c: 3}).map(function(item, index){ return item * 2; }); //timesTwo now holds an object containing: {a: 2, b: 4, c: 6};
47
Syntax:
var filteredHash = myHash.filter(fn[, bind]);
Arguments:
1. fn - (function) The function to test each element of the Hash. This function is passed the value and its key in the Hash. 2. bind - (object, optional) The object to use as 'this' in the function. For more information see [Function:bind][]. Argument: fn
Syntax:
fn(value, key, hash)
Arguments:
1. value - (mixed) The current value in the hash. 2. key - (string) The current value's key in the hash. 3. hash - (hash) The actual hash.
Returns:
Examples:
var biggerThanTwenty = new Hash({a: 10, b: 20, c: 30}).filter(function(value, key){ return value > 20; }); //biggerThanTwenty now holds an object containing: {c: 30}
Syntax:
var allPassed = myHash.every(fn[, bind]);
48
Arguments:
1. fn - (function) The function to test each element of the Hash. This function is passed the value and its key in the Hash. 2. bind - (object, optional) The object to use as 'this' in the function. For more information see [Function:bind]. Argument: fn
Syntax:
fn(value, key, hash)
Arguments:
1. value - (mixed) The current value in the hash. 2. key - (string) The current value's key in the hash. 3. hash - (hash) The actual hash.
Returns:
(boolean) If every value in the Hash satisfies the provided testing function, returns true. Otherwise, returns false.
Examples:
var areAllBigEnough = ({a: 10, b: 4, c: 25, d: 100}).every(function(value, key){ return value > 20; }); //areAllBigEnough = false
Syntax:
var anyPassed = myHash.any(fn[, bind]);
Arguments:
1. fn - (function) The function to test each element of the Hash. This function is passed the value and its key in the Hash. 2. bind - (object, optional) The object to use as 'this' in the function. For more information see [Function:bind][].
49
Argument: fn
Syntax:
fn(value, key, hash)
Arguments:
1. value - (mixed) The current value in the hash. 2. key - (string) The current value's key in the hash. 3. hash - (hash) The actual hash.
Returns:
(boolean) If any value in the Hash satisfies the provided testing function, returns true. Otherwise, returns false.
Examples:
var areAnyBigEnough = ({a: 10, b: 4, c: 25, d: 100}).some(function(value, key){ return value > 20; }); //isAnyBigEnough = true
Syntax:
myHash.getClean();
Returns:
Examples:
var hash = new Hash({ 'name': 'John', 'lastName': 'Doe' }); hash = hash.getClean(); // hash doesnt contain Hash prototypes anymore hash.each() //error!
50
Syntax:
var keys = myHash.getKeys();
Returns:
Syntax:
var values = myHash.getValues();
Returns:
Syntax:
var queryString = myHash.toQueryString();
Arguments:
1. source - (object) The object to generate the query string from.
Returns:
Examples:
Using Hash generic:
Hash.toQueryString({apple: "red", lemon: "yellow"}); //returns "apple=red&lemon=yellow"
51
52
Utility Functions
Function: $H
Shortcut for the new Hash.
See Also:
Hash
53
Native: Event
MooTools Event Methods.
Arguments:
1. event - (event) An HTMLEvent Object. 2. win - (window, optional: defaults to window) The context of the event. Properties:
shift - (boolean) True if the user pressed the shift key. control - (boolean) True if the user pressed the control key. alt - (boolean) True if the user pressed the alt key. meta - (boolean) True if the user pressed the meta key. wheel - (number) The amount of third button scrolling. code - (number) The keycode of the key pressed. page.x - (number) The x position of the mouse, relative to the full window. page.y - (number) The y position of the mouse, relative to the full window. client.x - (number) The x position of the mouse, relative to the viewport. client.y - (number) The y position of the mouse, relative to the viewport. key - (string) The key pressed as a lowercase string. key can be 'enter', 'up', 'down', 'left', 'right', 'space', 'backspace', 'delete', and 'esc'. target - (element) The event target, not extended with $ for performance reasons. relatedTarget - (element) The event related target, NOT extended with $.
Examples:
$('myLink').addEvent('keydown', function(event){ //The passed event parameter is already an instance of the Event class. alert(event.key); //Returns the lowercase letter pressed. alert(event.shift); //Returns true if the key pressed is shift. if (event.key == 's' && event.control) alert('Document saved.'); //Executes if the user hits Ctr+S. });
Notes:
Accessing event.page / event.client requires the page to be in Standards Mode. Every event added with addEvent gets the mootools method automatically, without the need to manually instance it.
54
Syntax:
myEvent.stop();
Returns:
Examples:
HTML:
<a id="myAnchor" href="http://google.com/">Visit Google.com</a>
JavaScript
$('myAnchor').addEvent('click', function(event){ event.stop(); //Prevents the browser from following the link. this.setText("Where do you think you're going?"); //'this' is Element that fires the Event. (function(){ this.setText("Instead visit the Blog.").set('href', 'http://blog.mootools.net'); }).delay(500, this); });
Notes:
Returning false within the function can also stop the propagation of the Event.
See Also:
Syntax:
myEvent.stopPropagation();
55
Returns:
Examples:
"#myChild" does not cover the same area as myElement. Therefore, the 'click' differs from parent and child depending on the click location:
HTML:
<div id="myElement"> <div id="myChild"></div> </div>
JavaScript
$('myElement').addEvent('click', function(){ alert('click'); return false; // equivalent to stopPropagation. }); $('myChild').addEvent('click', function(event){ event.stopPropagation(); // this will prevent the event to bubble up, and fire the parent's click event. });
See Also:
Syntax:
myEvent.preventDefault();
Returns:
Examples:
HTML:
<form> <input id="myCheckbox" type="checkbox" /> </form>
56
JavaScript
$('myCheckbox').addEvent('click', function(event){ event.preventDefault(); //Will prevent the checkbox from being "checked". });
See Also:
57
Hash: Event.Keys
Additional Event key codes can be added by adding properties to the Event.Keys Hash. Example:
Event.Keys.shift = 16; $('myInput').addEvent('keydown', function(event){ if (event.key == "shift") alert("You pressed shift."); });
58
Native: Class
The base Class of the MooTools framework.
Arguments:
1. properties - (object) The collection of properties that apply to the Class. Also accepts some special properties such as Extends, Implements, and initialize (see below). Property: Extends
The methods of This Class that have the same name as the Extends Class, will have a parent property, that allows you to call the other overridden method. Property: Implements
(object) A passed object's properties will be copied into this Class. (class) The properties of a passed Class will be copied into the target Class. (array) An array of objects or Classes, the properties of which will be copied into this Class.
Implements is similar to Extends, except that it overrides properties without inheritance. Useful when implementing a default set of properties in multiple Classes. Property: initialize
(function) The initialize function will be the constructor for this class when new instances are created.
Returns:
59
Examples:
Class Example:
var Cat = new Class({ initialize: function(name){ this.name = name; } }); var myCat = new Cat('Micia'); alert(myCat.name); //alerts 'Micia' var Cow = new Class({ initialize: function(){ alert('moooo'); } }); var Effie = new Cow($empty); //Will not alert 'moooo', because the initialize method is overridden by the $empty function.
Extends Example:
var Animal = new Class({ initialize: function(age){ this.age = age; } }); var Cat = new Class({ Extends: Animal, initialize: function(name, age){ this.parent(age); //will call initalize of Animal this.name = name; } }); var myCat = new Cat('Micia', 20); alert(myCat.name); //Alerts 'Micia'. alert(myCat.age); //Alerts 20.
Implements Example:
var Animal = new Class({ initialize: function(age){ this.age = age; } }); var Cat = new Class({ Implements: Animal, setName: function(name){ this.name = name } }); var myAnimal = new Cat(20); myAnimal.setName('Micia'); alert(myAnimal.name); //Alerts 'Micia'.
60
Syntax:
MyClass.implement(properties);
Arguments:
1. properties - (object) The properties to add to the base Class.
Examples:
var Animal = new Class({ initialize: function(age){ this.age = age; } }); Animal.implement({ setName: function(name){ this.name = name; } }); var myAnimal = new Animal(20); myAnimal.setName('Micia'); alert(myAnimal.name); //alerts 'Micia'
61
Class: Chain
A Utility Class which executes functions one after another, with each function firing after completion of the previous. Its methods can be implemented with Class:implement into any Class, and it is currently implemented in Fx and Request. In Fx, for example, it is used to create custom, complex animations.
Stand alone
var myChain = new Chain;
Example:
var Todo = new Class({ Implements: Chain, initialize: function(){ this.chain.apply(this, arguments); } }); var myTodoList = new Todo( function(){ alert('get groceries'); }, function(){ alert('go workout'); }, function(){ alert('code mootools documentation until eyes close involuntarily'); }, function(){ alert('sleep'); } );
See Also:
Class
62
Syntax:
myClass.chain(fn[, fn2[, fn3[, ...]]]);
Arguments:
1. Any number of functions.
Returns:
(object) The current Class instance. Calls to chain can also be chained.
Example:
//Fx.Tween has already implemented the Chain class because of inheritance of the Fx class. var myFx = new Fx.Tween('myElement', 'opacity'); myFx.start(1,0).chain( //Notice that "this" refers to the calling object (in this case, the myFx object). function(){ this.start(0,1); }, function(){ this.start(1,0); }, function(){ this.start(0,1); } ); //Will fade the Element in and out three times.
See Also:
Fx, Fx.Tween
Syntax:
myClass.callChain([any arguments]);
Arguments:
1. Any arguments passed in will be passed to the "next" function.
Returns:
63
Example:
var myChain = new Chain(); myChain.chain( function(){ alert('do dishes'); }, function(){ alert('put away clean dishes'); } ); myChain.callChain(); //Will alert 'do dishes'. myChain.callChain(); //Will alert 'put away clean dishes'.
Syntax:
myClass.clearChain();
Returns:
Example:
var myFx = Fx.Tween('myElement', 'color'); //Fx.Tween inherited Fx's implementation of Chain. myFx.chain(function(){ while(true) alert("D'oh!"); }); //Chains an infinite loop of alerts. myFx.clearChain(); //Cancels the infinite loop of alerts before allowing it to begin.
See Also:
Fx, Fx.Tween
64
Class: Events
A Utility Class. Its methods can be implemented with Class:implement into any Class. In Fx, for example, this Class is used to allow any number of functions to be added to the Fx events, like onComplete, onStart, and onCancel. Events in a Class that implements Events must be either added as an option or with addEvent, not directly through .options.onEventName.
Syntax:
For new classes:
var MyClass = new Class({ Implements: Events });
Implementing:
This class can be implemented into other classes to add its functionality to them. Events has been designed to work well with the Options class when the option property begins with 'on' and is followed by a capital letter (e.g. 'onComplete').
Example:
var Widget = new Class({ Implements: Events, initialize: function(element){ ... }, complete: function(){ this.fireEvent('onComplete'); } }); var myWidget = new Widget(); myWidget.addEvent('onComplete', myFunction);
See Also:
Class, Options
65
Syntax:
myClass.addEvent(type, fn[, internal]);
Arguments:
1. type - (string) The type of event (e.g. 'onComplete'). 2. fn - (function) The function to execute. 3. internal - (boolean, optional) Sets the function property: internal to true. Internal property is used to prevent removal.
Returns:
Example:
var myFx = new Fx.Tween('element', 'opacity'); myFx.addEvent('onStart', myStartFunction);
Syntax:
myClass.addEvents(events);
Arguments:
1. events - (object) An object with key/value representing: key the event name (e.g. 'onStart'), and value the function that is called when the Event occurs.
Returns:
Example:
var myFx = new Fx.Tween('element', 'opacity'); myFx.addEvents({ 'onStart': myStartFunction, 'onComplete': function() { alert('Done.'); } });
66
Syntax:
myClass.fireEvent(type[, args[, delay]]);
Arguments:
1. type - (string) The type of event (e.g. 'onComplete'). 2. args - (mixed, optional) The argument(s) to pass to the function. To pass more than one argument, the arguments must be in an array. 3. delay - (number, optional) Delay in miliseconds to wait before executing the event (defaults to 0).
Returns:
Example:
var Widget = new Class({ Implements: Events, initialize: function(arg1, arg2){ //... this.fireEvent("onInitialize", [arg1, arg2], 50); } });
Syntax:
myClass.removeEvent(type, fn);
Arguments:
1. type - (string) The type of event (e.g. 'onComplete'). 2. fn - (function) The function to remove.
Returns:
67
Notes:
If the function has the property internal and is set to true, then the event will not be removed.
Syntax:
myClass.removeEvents([type]);
Arguments:
1. type - (string, optional) The type of event to remove (e.g. 'onComplete'). If no type is specified, removes all events of all types.
Returns:
Example:
var myFx = new Fx.Tween('myElement', 'opacity'); myFx.removeEvents('onComplete');
Notes:
68
Class: Options
A Utility Class. Its methods can be implemented with Class:implement into any Class. Used to automate the setting of a Class instance's options. Will also add Class Events when the option property begins with 'on' and is followed by a capital letter (e.g. 'onComplete').
Syntax:
For new classes:
var MyClass = new Class({Implements: Options});
Syntax:
myClass.setOptions([options]);
Arguments:
1. options - (object, optional) The user defined options to merge with the defaults.
Returns:
69
Example:
var Widget = new Class({ Implements: Options, options: { color: '#fff', size: { width: 100, height: 100 } }, initialize: function(options){ this.setOptions(options); } }); var myWidget = new Widget({ color: '#f00', size: { width: 200 } }); //myWidget.options is now: {color: #f00, size: {width: 200, height: 100}}
Notes:
Relies on the default options of a Class defined in its options property. If a Class has Events implemented, every option beginning with 'on' and followed by a capital letter (e.g. 'onComplete') becomes a Class instance event, assuming the value of the option is a function.
70
Native: Window
The following functions are treated as Window methods.
Function: $
The dollar function has a dual purpose: Getting the element by its id, and making an element in Internet Explorer "grab" all the Element methods.
Syntax:
var myElement = $(el);
Arguments:
1. el - (mixed) A string containing the id of the DOM element desired or a reference to an actual DOM element.
Returns:
Examples:
Get a DOM Element by ID:
var myElement = $('myElement');
Notes:
This method is useful when it's unclear if working with an actual element or an id. It also serves as a shorthand for document.getElementById(). In Internet Explorer, the Element is extended the first time $ is called on it, and all the Element Methods become available. Browsers with native HTMLElement support, such as Safari, Firefox, and Opera, apply all the Element Methods to every DOM element automatically. Because MooTools detects if an element needs to be extended or not, this function may be called on the same Element many times with no ill effects.
71
Function: $$
Selects and extends DOM elements. Elements arrays returned with $$ will also accept all the Element methods.
Syntax:
var myElements = $$(aTag[, anElement[, Elements[, ...]);
Arguments:
Any number of the following as arguments are accepted: HTMLCollections, arrays of elements, elements, or strings as selectors.
Returns:
Examples:
Get Elements by Their Tag Names:
$$('a'); //Returns all anchor elements in the page. $$('a', 'b'); //Returns all anchor and bold tags on the page.
Notes:
When Selectors is loaded, $$ will also accept CSS Selectors. Otherwise, the only selectors supported are tag names. If an expression doesn't find any elements, an empty array will be returned. The return type of element methods run through $$ is always an array, regardless of the amount of results.
See Also:
See Selectors for documentation on selectors for use anywhere they are accepted throughout the framework. 72
Native: Element
Custom Native to allow all of its methods to be used with any extended DOM Element.
Syntax:
var myEl = new Element(element[, properties]);
Arguments:
1. element - (mixed) The tag name for the Element to be created or an actual DOM element. 2. properties - (object, optional) Calls the Single Argument version of Element:set with the properties object passed in.
Returns:
Examples:
var myAnchor = new Element('a', { 'href': 'http://mootools.net', 'class': 'myClass', 'html': 'Click me!', 'styles': { 'display': 'block', 'border': '1px solid black' }, 'events': { 'click': function(){ alert('clicked'); }, 'mouseover': function(){ alert('mouseovered'); } } });
See Also:
$, Element:set
73
Syntax:
var myElement = myElement.getElement(tag);
Arguments:
1. tag - (string) Tag name of the element to find.
Returns:
(mixed) If a match is found, the Element will be returned. Otherwise, returns null.
Examples:
var firstDiv = $(document.body).getElement('div');
Notes:
This method is also available for Document instances. This method gets replaced when Selectors is included. Selectors enhances Element:getElement so that it matches based on CSS selectors.
See Also:
See Selectors for documentation on selectors for use anywhere they are accepted throughout the framework.
Syntax:
var myElements = myElement.getElements(tag);
Arguments:
1. tag - (string) String of the tag to match.
74
Returns:
Examples:
var allAnchors = $(document.body).getElements('a');
Notes:
This method is also available for Document instances. This method gets replaced when Selectors is included. Selectors enhances Element:getElements so that it matches based on CSS selectors.
See Also:
See Selectors for documentation on selectors for use anywhere they are accepted throughout the framework.
Syntax:
var myElement = anElement.getElementById(id);
Arguments:
1. id - (string) The ID of the Element to find.
Returns:
Examples:
var myChild = $('myParent').getElementById('myChild');
Notes:
This method is not provided for Document instances as document.getElementById is provided natively.
Syntax:
myElement.set(arguments);
Arguments:
Two Arguments (property, value) 1. property - (string) The string key from the Element.Properties Hash representing the property to set. 2. value - (mixed) The value to set for the specified property. One Argument (properties) 1. properties - (object) Object with its keys/value pairs representing the properties and values to set for the Element (as described below).
Returns:
Examples:
With Property and Value:
$('myElement').set('text', 'text goes here'); $('myElement').set('class', 'active'); //The 'styles' property passes the object to Element:setStyles. var body = $(document.body).set('styles', { 'font': '12px Arial', 'color': 'blue' });
With an Object:
var myElement = $('myElement').set({ //The 'styles' property passes the object to Element:setStyles. 'styles': { 'font': '12px Arial', 'color': 'blue', 'border': '1px solid #f00' }, //The 'events' property passes the object to Element:addEvents. 'events': { 'click': function(){ alert('click'); }, 'mouseover': function(){ this.addClass('over') } }, //Any other property uses Element:setProperty. 'id': 'documentBody' });
Notes:
All the property arguments are passed to the corresponding method of the Element.Properties Hash. If no matching property is found in Element.Properties, it falls back to Element:setProperty.
76
See Also:
Syntax:
myElement.get(property);
Arguments:
1. property - (string) The string key from the Element.Properties Hash representing the property to get.
Returns:
(mixed) The result of calling the corresponding 'get' function in the Element.Properties Hash.
Examples:
Using Custom Getters:
var tag = $('myDiv').get('tag'); //Returns "div".
Notes:
If the corresponding accessor doesn't exist in the Element.Properties Hash, the result of Element:getProperty on the property passed in is returned.
See Also:
77
Syntax:
myElement.erase(property);
Arguments:
1. property - (string) The string key from the Element.Properties Hash representing the property to erase.
Returns:
(mixed) The result of calling the corresponding 'erase' function in the Element.Properties Hash.
Examples:
$('myDiv').erase('id'); //Removes the id from myDiv. $('myDiv').erase('class'); //myDiv element no longer has any class names set.
Note:
If the corresponding eraser doesn't exist in the Element.Properties Hash, Element:removeProperty is called with the property passed in.
See Also:
Syntax:
myElement.match(tag);
Arguments:
1. tag - (string) The tag name to test against this element.
78
Returns:
(boolean) If the element has the specified tag name, returns true. Otherwise, returns false.
Examples:
$('myDiv').match('div'); //Returns true if myDiv is a div.
Notes:
See Element:match. This method is overwritten by a more powerful version when Selectors is included.
Syntax:
myElement.inject(el[, where]);
Arguments:
1. el - (mixed) el can be the id of an element or an element. 2. where - (string, optional: defaults to 'bottom') The place to inject this Element. Can be 'top', 'bottom', 'after', or 'before'.
Returns:
Examples:
JavaScript
var myFirstElement = new Element('div', {id: 'myFirstElement'}); var mySecondElement = new Element('div', {id: 'mySecondElement'}); var myThirdElement = new Element('div', {id: 'myThirdElement'});
Resulting HTML
<div id="myFirstElement"></div> <div id="mySecondElement"></div> <div id="myThirdElement"></div>
79
Resulting HTML
<div id="mySecondElement"> <div id="myFirstElement"></div> </div>
Resulting HTML
<div id="mySecondElement"> <div id="myThirdElement"></div> <div id="myFirstElement"></div> </div>
Inject before:
JavaScript
myFirstElement.inject(mySecondElement, 'before');
Resulting HTML
<div id="myFirstElement"></div> <div id="mySecondElement"></div>
Inject After:
JavaScript
myFirstElement.inject(mySecondElement, 'after');
80
Resulting HTML
<div id="mySecondElement"></div> <div id="myFirstElement"></div>
See Also:
Element:adopt, Element:grab, Element:wraps
Syntax:
myElement.grab(el[, where]);
Arguments:
1. el - (mixed) el can be the id of an element or an element. 2. where - (string, optional: default 'bottom') The place to append this Element. Can be 'top' or 'bottom'.
Returns:
Examples:
JavaScript
var myFirstElement = new Element('div', {id: 'myFirstElement'}); var mySecondElement = new Element('div', {id: 'mySecondElement'}); myFirstElement.grab(mySecondElement);
Resulting HTML
<div id="myFirstElement"> <div id="mySecondElement"></div> </div>
See Also:
Element:adopt, Element:inject, Element:wraps
81
Syntax:
myParent.adopt(el[, others]);
Arguments:
1. el - (mixed) The id of an element, an Element, or an array of elements. 2. others - (mixed, optional) One or more additional Elements separated by a comma or as an array.
Returns:
Examples:
JavaScript
var myFirstElement = new Element('div', {id: 'myFirstElement'}); var mySecondElement = new Element('a', {id: 'mySecondElement'}); var myThirdElement = new Element('ul', {id: 'myThirdElement'}); myParent.adopt(myFirstElement); myParent2.adopt(myFirstElement, 'mySecondElement'); myParent3.adopt([myFirstElement, mySecondElement, myThirdElement]);
Resulting HTML
<div id="myParent"> <div id="myFirstElement" /> </div> <div id="myParent2"> <div id="myFirstElement" /> <a /> </div> <div id="myParent3"> <div id="myFirstElement" /> <a /> <ul /> </div>
See Also:
Element:grab, Element:inject, Element:wraps
82
Syntax:
myParent.wrap(el[, where]);
Arguments:
1. el - (mixed) The id of an element, an Element, or an array of elements. 2. where - (string, optional: default 'bottom') The place to insert the passed in element. Can be 'top' or 'bottom'.
Returns:
Syntax:
myElement.appendText(text);
Arguments:
1. text - (string) The text to append. 2. where - (string, optional: default 'bottom') The position to inject the text to.
Returns:
Examples:
HTML
<div id="myElement">Hey.</div>
83
JavaScript
$('myElement').appendText(' Howdy.');
Resulting HTML
<div id="myElement">Hey. Howdy.</div>
Syntax:
var removedElement = myElement.dispose();
Returns:
(element) This Element. Useful to always grab the return from this function, as the element could be injected back.
Examples:
HTML
<div id="myElement"></div> <div id="mySecondElement"></div>
JavaScript
$('myElement').dispose();
Resulting HTML
<div id="mySecondElement"></div>
See Also:
MDC Element:removeChild
84
Syntax:
var copy = myElement.clone([contents, keepid]);
Arguments:
1. contents - (boolean, optional: defaults to true) When true the Element is cloned with childNodes. 2. keepid - (boolean, optional: defaults to false) When true the cloned Element keeps the id attribute, if present. Same goes for any of the cloned childNodes.
Returns:
Examples:
HTML
<div id="myElement"></div>
JavaScript
//Clones the Element and appends the clone after the Element. var clone = $('myElement').clone().injectAfter('myElement');
Resulting HTML
<div id="myElement">ciao</div> <div>ciao</div>
Note:
The returned Element does not have an attached events. To clone the events use Element:cloneEvents. The clone element and its children are stripped of ids, unless otherwise specified by the keepid parameter.
See Also:
Element:cloneEvents.
85
Syntax:
var element = myElement.replaces(el);
Arguments:
1. el - (mixed) A string id representing the Element to be replaced with, or an Element reference.
Returns:
Examples:
$('myNewElement').replaces($('myOldElement')); //$('myOldElement') is gone, and $('myNewElement') is in its place.
See Also:
MDC Element:replaceChild
Syntax:
var result = myElement.hasClass(className);
Arguments:
1. className - (string) The class name to test.
Returns:
(boolean) Returns true if the Element has the class, otherwise false.
Examples:
HTML
<div id="myElement" class="testClass"></div>
86
JavaScript
$('myElement').hasClass('testClass'); //returns true
Syntax:
myElement.addClass(className);
Arguments:
1. className - (string) The class name to add.
Returns:
Examples:
HTML
<div id="myElement" class="testClass"></div>
JavaScript
$('myElement').addClass('newClass');
Resulting HTML
<div id="myElement" class="testClass newClass"></div>
Syntax:
myElement.removeClass(className);
87
Arguments:
1. className - (string) The class name to remove.
Returns:
Examples:
HTML
<div id="myElement" class="testClass newClass"></div>
JavaScript
$('myElement').removeClass('newClass');
Resulting HTML
<div id="myElement" class="testClass"></div>
Syntax:
myElement.toggleClass(className);
Arguments:
1. className - (string) The class to add or remove.
Returns:
Examples:
HTML
<div id="myElement" class="myClass"></div>
88
JavaScript
$('myElement').toggleClass('myClass');
Resulting HTML
<div id="myElement" class=""></div>
JavaScript
$('myElement').toggleClass('myClass');
Resulting HTML
<div id="myElement" class="myClass"></div>
Syntax:
var previousSibling = myElement.getPrevious([match]);
Arguments:
1. match - (string, optional): A tag name to match the the found element(s) with. If Selectors is included, a full CSS selector can be passed.
Returns:
Syntax:
var nextSibling = myElement.getNext([match]);
89
Arguments:
1. match - (string, optional): A tag name to match the found element(s) with. if Selectors is included, a full CSS selector can be passed.
Returns:
Syntax:
var firstElement = myElement.getFirst([match]);
Arguments:
1. match - (string, optional): A tag name to match the found element(s) with. if Selectors is included, a full CSS selector can be passed.
Returns:
Syntax:
var lastElement = myElement.getLast([match]);
Arguments:
1. match - (string, optional): A tag name to match the found element(s) with. if Selectors is included, a full CSS selector can be passed.
Returns:
90
Syntax:
var parent = myElement.getParent([match]);
Arguments:
1. match - (string, optional): A tag name to match the found element(s) with. if Selectors is included, a full CSS selector can be passed.
Returns:
Syntax:
var children = myElement.getChildren([match]);
Arguments:
1. match - (string, optional): A tag name to match the found element(s) with. if Selectors is included, a full CSS selector can be passed.
Returns:
(array) A Elements array with all of the Element's children, except the text nodes.
Syntax:
var result = myElement.hasChild(el);
91
Arguments:
1. el - (mixed) Can be an Element reference or string id.
Returns:
(boolean) Returns true if the passed in Element is a child of the Element, otherwise false.
Examples:
HTML
<div id="Darth_Vader"> <div id="Luke"></div> </div>
JavaScript
if ($('Darth_Vader').hasChild('Luke')) alert('Luke, I am your father.'); // tan tan tannn...
Syntax:
myElement.empty();
Returns:
Examples:
HTML
<div id="myElement"> <p></p> <span></span> </div>
JavaScript
$('myElement').empty();
92
Resulting HTML
<div id="myElement"></div>
Syntax:
myElement.destroy();
Returns:
(null)
Syntax:
var query = myElement.toQueryString();
Returns:
(string) A string representation of a all the input Elements' names and values.
Examples:
HTML
<form id="myForm" action="submit.php"> <input name="email" value="bob@bob.com" /> <input name="zipCode" value="90210" /> </form>
JavaScript
$('myForm').toQueryString(); //Returns "email=bob@bob.com&zipCode=90210".
93
Syntax:
var selected = mySelect.getSelected();
Returns:
Examples:
HTML
<select id="country-select" name="country"> <option value="US">United States</option <option value ="IT">Italy</option> </select>
JavaScript
$('country-select').getSelected(); //Returns whatever the user selected.
Note:
This method returns an array, regardless of the multiple attribute of the select element. If the select is single, it will return an array with only one item.
Syntax:
var myProp = myElement.getProperty(property);
Arguments:
Returns:
94
Examples:
HTML
<img id="myImage" src="mootools.png" title="MooTools, the compact JavaScript framework" alt="" />
JavaScript
var imgProps = $('myImage').getProperty('src'); //Returns: 'mootools.png'.
Syntax:
var myProps = myElement.getProperties(properties);
Arguments:
Returns:
Examples:
HTML
<img id="myImage" src="mootools.png" title="MooTools, the compact JavaScript framework" alt="" />
JavaScript
var imgProps = $('myImage').getProperties('id', 'src', 'title', 'alt'); //Returns: { id: 'myImage', src: 'mootools.png', title: 'MooTools, the compact JavaScript framework', alt: '' }
Arguments:
1. property - (string) The property to assign the value passed in. 2. value - (mixed) The value to assign to the property passed in. 95
Returns:
Examples:
HTML
<img id="myImage" />
JavaScript
$('myImage').setProperty('src', 'mootools.png');
Resulting HTML
<img id="myImage" src="mootools.png" />
Arguments:
1. properties - (object) An object with key/value pairs.
Returns:
Examples:
HTML
<img id="myImage" />
JavaScript
$('myImage').setProperties({ src: 'whatever.gif', alt: 'whatever dude' });
96
Resulting HTML
<img id="myImage" src="whatever.gif" alt="whatever dude" />
Syntax:
myElement.removeProperty(property);
Arguments:
1. property - (string) The attribute to remove.
Returns:
Examples:
HTML
<a id="myAnchor" href="#" onmousedown="alert('click');"></a>
JavaScript
//Eww... inline JavaScript is bad! Let's get rid of it. $('myAnchor').removeProperty('onmousedown');
Resulting HTML
<a id="myAnchor" href="#"></a>
Syntax:
myElement.removeProperties(properties);
97
Arguments:
1. properties - (strings) The attributes to remove, separated by comma.
Returns:
Examples:
HTML
<a id="myAnchor" href="#" title="hello world"></a>
JavaScript
$('myAnchor').removeProperties('id', 'href', 'title');
Resulting HTML
<a></a>
Syntax:
myElement.store(key, value);
Arguments:
1. key - (string) The key you want to assign to the stored value. 2. value - (mixed) Any value you want to store.
Returns:
Example:
$('element').store('someProperty', someValue);
98
Syntax:
myElement.retrieve(key);
Arguments:
1. key - (string) The key you want to retrieve from the storage.
Returns:
Example:
$('element').retrieve('someProperty'); // returns someValue (see example above)
99
Hash: Element.Properties
This Hash contains the functions that respond to the first argument passed in Element:get, Element:set and Element:erase.
Note:
Automatically returns the element for setters.
Using an Object:
Additionally, you can access these custom getters and setters using an object as the parameter for the set method. Example:
//Using set: $(divElement).set({html: '<p>Hello <em>People</em>!</p>', style: 'background:red'}); //For new Elements (works the same as set): new Element('input', {type: 'checkbox', checked: true, disabled: true});
100
Syntax:
myElement.set('html', [htmlString[, htmlString2[, htmlString3[, ..]]]);
Examples:
HTML
<div id="myElement"></div>
JavaScript
$('myElement').set('html', '<div></div>', '<p></p>');
Resulting HTML
<div id="myElement"> <div></div> <p></p> </div>
Getter:
Returns the inner HTML of the Element. Syntax:
myElement.get('html');
Returns:
Syntax:
myElement.set('text', text);
Arguments: 1. text - (string) The new text content for the Element. Returns:
Examples:
HTML
<div id="myElement"></div>
JavaScript
$('myElement').set('text', 'some text'); //The text of myElement is now 'some text'.
Resulting HTML
<div id="myElement">some text</div>
Getter:
Gets the inner text of the Element. Syntax:
var myText = myElement.get('text');
Returns:
Examples:
HTML
<div id="myElement">my text</div>
102
JavaScript
var myText = $('myElement').get('text'); //myText = 'my text'.
Returns:
Examples:
HTML
<img id="myImage" />
JavaScript
var myTag = $('myImage').get('tag'); // myTag = 'img'.
103
Native: IFrame
Custom Native to create and easily work with IFrames.
Syntax:
var myIFrame = new IFrame([el][, props]);
Arguments:
1. el - (mixed, optional) The id of the IFrame to be converted, or the actual IFrame element. If its not passed, a new IFrame will be created (default). 2. props - (object, optional) The properties to be applied to the new IFrame. Same as Element:constructor props argument.
Returns:
Examples:
var myIFrame = new IFrame({ src: 'http://mootools.net/', styles: { width: 800, height: 600, border: '1px solid #ccc' }, events: { mouseenter: function(){ alert('Welcome aboard.'); }, mouseleave: function(){ alert('Goodbye!'); }, load: function(){ alert('The iframe has finished loading.'); } } });
104
Notes:
If the IFrame is from the same domain as the "host", its document and window will be extended with MooTools functionalities, allowing you to fully use MooTools within it. If the IFrame already exists and has a different name than id, the name will be made the same as the id. If the IFrame is from a different domain, its window and document will not be extended with MooTools methods.
105
Native: Elements
The Elements class allows Element methods to work on an Elements array, as well as Array Methods.
Arguments:
1. elements - (mixed) An array of elements or an HTMLCollection Object.
Returns:
(array) An extended array with the Element, Elements and Array methods.
Examples:
Set Every Paragraph's Color to Red:
$$('p').each(function(el){ el.setStyle('color', 'red'); }); //Because $$('myselector') also accepts Element methods, the below //example has the same effect as the one above. $$('p').setStyle('color', 'red');
Notes:
In MooTools, every DOM function which returns a collection of nodes (such as $$) returns the nodes as instances of Elements. Because Elements is an Array, it accepts all the Array methods, while giving precedence to Element and Elements methods. Every node of the Elements instance has all the Element methods.
See Also:
106
Syntax:
var filteredElements = elements.filter(selector);
Arguments:
1. selector - (mixed) A single CSS selector.
Returns:
107
Native: Element
Custom Native to allow all of its methods to be used with any DOM element via the dollar function . These methods are also available on window and document.
Notes:
Internet Explorer fires element events in random order if they are not fired by Element:fireEvent.
Syntax:
myElement.addEvent(type, fn);
Arguments:
1. type - (string) The event name to monitor ('click', 'load', etc) without the prefix 'on'. 2. fn - (function) The function to execute.
Returns:
Examples:
HTML:
<div id="myElement">Click me.</div>
JavaScript
$('myElement').addEvent('click', function(){ alert('clicked!'); });
Notes:
You can stop the Event by returning false in the listener or calling Event:stop. This method is also attached to Document and Window.
See Also:
108
Syntax:
myElement.removeEvent(type, fn);
Arguments:
1. type - (string) The event name. 2. fn - (function) The function to remove.
Returns:
Examples:
Standard usage:
var destroy = function(){ alert('Boom: ' + this.id); } // this refers to the Element. $('myElement').addEvent('click', destroy); // later $('myElement').removeEvent('click', destroy);
Notes:
When the function is added using Function:bind or Function:pass, etc, a new reference is created. For removeEvent to work, you must pass a reference to the exact function to be removed. This method is also attached to Document and Window.
109
Syntax:
myElement.addEvents(events);
Arguments:
1. events - (object) An object with key/value representing: key the event name, and value the function that is called when the Event occurs.
Returns:
Examples:
$('myElement').addEvents({ 'mouseover': function(){ alert('mouseover'); }, 'click': function(){ alert('click'); } });
Notes:
See Also:
Element:addEvent
Syntax:
myElements.removeEvents([type]);
Arguments:
1. type - (string, optional) The event name (e.g. 'click'). If undefined, removes all events.
Returns:
110
Examples:
var myElement = $('myElement'); myElement.addEvents({ 'mouseover': function(){ alert('mouseover'); }, 'click': function(){ alert('click'); } }); myElement.addEvent('click': function(){ alert('clicked again'); }); myElement.addEvent('click': function(){ alert('clicked and again :('); }); //addEvent will keep appending each function. //Unfortunately for the visitor, that'll be three alerts they'll have to click on. myElement.removeEvents('click'); // This saves the visitor's finger by removing every click event.
Notes:
See Also:
Element:removeEvent
Syntax:
myElement.fireEvent(type[, args[, delay]]);
Arguments:
1. type - (string) The event name (e.g. 'click') 2. args - (mixed, optional) Array or single object, arguments to pass to the function. If more than one argument, must be an array. 3. delay - (number, optional) Delay (in ms) to wait to execute the event.
Returns:
Examples:
// Fires all the added 'click' events and passes the Element 'anElement' after one second. $('myElement').fireEvent('click', $('anElement'), 1000);
111
Notes:
This will not fire the DOM Event (this concerns all inline events ie. onmousedown=".."). This method is also attached to Document and Window.
Syntax:
myElement.cloneEvents(from[, type]);
Arguments:
1. from - (element) Copy all events from this Element. 2. type - (string, optional) Copies only events of this type. If null, copies all events.
Returns:
Examples:
var myElement = $('myElement'); var myClone = myElement.clone().cloneEvents(myElement); //clones the element and its events
Notes:
Hash: Element.Events
You can add additional custom events by adding properties (objects) to the Element.Events Hash Arguments: The Element.Events.yourproperty (object) can have: 1. base - (string, optional) the base event the custom event will listen to. Its not optional if condition is set. 2. condition - (function, optional) the condition from which we determine if the custom event can be fired. Is bound to the element you add the event to. The Event is passed in. 3. onAdd - (function, optional) the function that will get fired when the custom event is added. Is bound to the element you add the event to. 4. onRemove - (function, optional) the function that will get fired when the custom event is removed. Is bound to the element you add the event to.
112
Examples:
Element.Events.shiftclick = { base: 'click', //we set a base type condition: function(event){ //and a function to perform additional checks. return (event.shift == true); //this means the event is free to fire } }; $('myInput').addEvent('shiftclick', function(event){ log('the user clicked the left mouse button while holding the shift key'); });
Notes:
There are different types of custom Events you can create: 1. Custom Events with only base: they will just be a redirect to the base event. 2. Custom Events with base and condition: they will be redirect to the base event, but only fired if the condition is met. 3. Custom Events with onAdd and/or onRemove and any other of the above: they will also perform additional functions when the event is added/removed.
Warning: If you use the condition option you NEED to specify a base type, unless you plan to overwrite a native event. (highly unrecommended: use only when you know exactly what you're doing).
Custom Events
Event: mouseenter
This event fires when the mouse enters the area of the DOM Element and will not be fired again if the mouse crosses over children of the Element (unlike mouseover). Examples:
$('myElement').addEvent('mouseenter', myFunction);
See Also:
Element:addEvent
Event: mouseleave
This event fires when the mouse leaves the area of the DOM Element and will not be fired if the mouse crosses over children of the Element (unlike mouseout). Examples:
$('myElement').addEvent('mouseleave', myFunction);
113
See Also:
Element:addEvent
Event: mousewheel
This event fires when the mouse wheel is rotated; Examples:
$('myElement').addEvent('mousewheel', myFunction);
Notes:
This custom event just redirects DOMMouseScroll (Mozilla) to mousewheel (Opera, Internet Explorer), making it work across browsers.
See Also:
Element:addEvent
114
Native: Element
Custom Native to allow all of its methods to be used with any DOM element via the dollar function $.
Syntax:
myElement.setStyle(property, value);
Arguments:
1. property - (string) The property to set. 2. value - (mixed) The value to which to set it. Numeric values of properties requiring a unit will automatically be appended with 'px'.
Returns:
Example:
//Both lines have the same effect. $('myElement').setStyle('width', '300px'); //The width is now 300px. $('myElement').setStyle('width', 300); //The width is now 300px.
Notes:
All number values will automatically be rounded to the nearest whole number.
Syntax:
var style = myElement.getStyle(property);
Arguments:
1. property - (string) The css style property you want to retrieve.
115
Returns:
Examples:
$('myElement').getStyle('width'); //Returns "300px". $('myElement').getStyle('width').toInt(); //Returns 300.
Syntax:
myElement.setStyles(styles);
Arguments:
1. styles - (object) An object of property/value pairs for all the styles to apply.
Returns:
Example:
$('myElement').setStyles({ border: '1px solid #000', width: 300, height: 400 });
See Also:
Element:getStyle
Syntax:
var styles = myElement.getStyles(property[, property2[, property3[, ...]]]);
116
Arguments:
1. properties - (strings) Any number of style properties.
Returns:
(object) An key/value object with the CSS styles as computed by the browser.
Examples:
$('myElement').getStyles('width', 'height', 'padding'); //returns {width: "10px", height: "10px", padding: "10px 0px 10px 0px"}
See Also:
Element:getStyle
117
Native: Element
Custom Native to allow all of its methods to be used with any DOM element via the dollar function $.
Note:
These methods don't take into consideration the body element margins and borders. If you need margin/borders on the body, consider adding a wrapper div, but always reset the margin and borders of body to 0.
Credits:
Element positioning based on the qooxdoo code and smart browser fixes, LGPL License. Viewport dimensions based on YUI code, BSD License.
Syntax:
myElement.scrollTo(x, y);
Arguments:
1. x - (number) The x coordinate. 2. y - (number) The y coordinate.
Example:
$('myElement').scrollTo(0, 100);
See Also:
Syntax:
myElement.getSize();
118
Returns:
(object) An object containing the width (as x) and the height (as y) of the target Element.
Example:
var size = myElement.getSize(); alert("The element is "+size.x+" pixels wide and "+size.y+"pixels high.");
Syntax:
myElement.getScrollSize();
Returns:
Example:
var scroll = $('myElement').getScrollSize(); alert('My element can scroll to ' + scroll.y + 'px'); //alerts 'My element can scroll down to 820px'
See Also:
MDC Element:scrollLeft, MDC Element:scrollTop, MDC Element:offsetWidth, MDC Element:offsetHeight, MDC Element:scrollWidth, MDC Element:scrollHeight
Syntax:
myElement.getScroll();
Returns:
(object) An object containing the x and y dimensions of the target Element's scroll.
119
Example:
var scroll = $('myElement').getScroll(); alert('My element is scrolled down ' + scroll.y + 'px'); //alerts 'My element is scrolled down to 620px'
Syntax:
myElement.getPosition(relative);
Arguments:
relative - (Element, defaults to the document) If set, the position will be relative to this Element.
Returns:
Example:
$('element').getPosition(); //returns {x: 100, y: 500};
See Also:
Syntax:
myElement.getCoordinates(relative);
Arguments:
relative - (element, optional) if set, the position will be relative to this element, otherwise relative to the document.
Returns:
(object) An object containing the Element's current: top, left, width, height, right, and bottom.
120
Example:
var myValues = $('myElement').getCoordinates();
Returns:
{ top: 50, left: 100, width: 200, height: 300, right: 300, bottom: 350 }
See Also:
Element:getPosition
121
Native: Element
Custom class to allow all of its methods to be used with any Selectors element via the dollar function $.
Syntax:
var myElements = myElement.getElements(selector);
Arguments:
1. selector - (string) The CSS Selector to match.
Returns:
Examples:
//Returns all anchors within myElement. $('myElement').getElements('a'); //Returns all input tags with name "dialog". $('myElement').getElements('input[name=dialog]'); //Returns all input tags with names ending with 'log'. $('myElement').getElements('input[name$=log]'); //Returns all email links (starting with "mailto:"). $('myElement').getElements('a[href^=mailto:]'); //Adds events to all Elements with the class name 'email'. $(document.body).getElements('a.email').addEvents({ 'mouseenter': function(){ this.href = 'real@email.com'; }, 'mouseleave': function(){ this.href = '#'; } });
Notes:
122
Syntax:
var anElement = myElement.getElement(selector);
Arguments:
1. selector - (string) The CSS Selector to match.
Returns:
Example:
var found = $('myElement').getElement('.findMe').setStyle('color', '#f00');
Note:
Function: $E
Alias for Element:getElement, using document as context.
Syntax:
var matched = myElement.match(selector);
Arguments:
1. selector - (string) Selector to match the Element to.
Returns:
123
Example:
//Returns true if the Element is a div named "somename". $('myElement').match('div[name=somename]');
124
Selectors.Pseudo
Some default Pseudo Selectors for Selectors.
See Also:
Selector: enabled
Matches all Elements that are enabled.
Usage:
':enabled'
Examples:
$$('*:enabled') $('myElement').getElements(':enabled');
Selector: empty
Matches all elements which are empty.
Usage:
':empty'
Example:
$$('div:empty');
Selector: contains
Matches all the Elements which contains the text.
Usage:
':contains(text)'
125
Variables:
Example:
$$('p:contains("find me")');
Selector: nth-child
Matches every nth child.
Usage:
Nth Expression:
':nth-child(nExpression)'
Variables:
Examples:
$$('#myDiv:nth-child(2n)'); //Returns every even child. $$('#myDiv:nth-child(n)'); //Returns all children. $$('#myDiv:nth-child(2n+1)') //Returns every odd child. $$('#myDiv:nth-child(4n+3)') //Returns Elements 3, 7, 11, 15, etc.
Only Child:
':nth-child(only)'
First Child:
'nth-child(first)'
126
Last Child:
'nth-child(last)'
Note:
This selector respects the w3c specifications, so it has 1 as its first child, not 0. Therefore nth-child(odd) will actually select the even children, if you think in zero-based indexes.
Selector: even
Matches every even child.
Usage:
':even'
Example:
$$('td:even');
Note:
This selector is not part of the w3c specification, therefore its index starts at 0. This selector is highly recommended over nth-child(even), as this will return the real even children.
Selector: odd
Matches every odd child.
Usage:
':odd'
Example:
$$('td:odd');
Note:
This selector is not part of the w3c specification, therefore its index starts at 0. This selector is highly recommended over nth-child(odd), as this will return the real odd children.
127
Selector: first
Matches the first child.
Usage:
':first-child'
Example:
$$('td:first-child');
Selector: last
Matches the last child.
Usage:
':last-child'
Example:
$$('td:last-child');
Selector: only
Matches an only child of its parent Element.
Usage:
':only-child'
Example:
$$('td:only-child');
128
Example:
window.addEvent('domready', function() { alert("The DOM is ready."); });
See Also:
Element.Event
129
Object: JSON
JSON parser and encoder.
See Also:
Syntax:
var myJSON = JSON.encode(obj);
Arguments:
1. obj - (object) The object to convert to string.
Returns:
Examples:
var fruitsJSON = JSON.encode({apple: 'red', lemon: 'yellow'}); // returns: '{"apple":"red","lemon":"yellow"}'
Syntax:
var object = JSON.decode(string[, secure]);
Arguments:
1. string - (string) The string to evaluate. 2. secure - (boolean, optional: defaults to false) If set to true, checks for any hazardous syntax and returns null if any found.
Returns:
Examples:
var myObject = JSON.decode('{"apple":"red","lemon":"yellow"}'); //returns: {apple: 'red', lemon: 'yellow'}
Credits:
131
Object: Cookie
Sets and accesses cookies.
Credits:
Options:
domain - (string: defaults to false) The domain the Cookie belongs to. path - (string: defaults to false) The path the Cookie belongs to. duration - (number: defaults to false) The duration of the Cookie before it expires, in days. If set to false or 0, the cookie will be a session cookie that expires when the browser is closed. secure - (boolean: defaults to false) Stored cookie information can be accessed only from a secure environment.
Notes:
In order to share the Cookie with pages located in a different path, the Cookie.options.domain value must be set.
Syntax:
var myCookie = Cookie.write(key, value[, options]);
Arguments:
1. key - (string) The key (or name) of the cookie. 2. value - (string) The value to set. Cannot contain semicolons. 3. options - (mixed, optional) See Cookie.
Returns:
(object) An object with the options, the key and the value. You can give it as first parameter to Cookie.remove.
Examples:
Saves the Cookie for the Duration of the Session:
var myCookie = Cookie.write('username', 'Harald');
132
Syntax:
var myCookie = Cookie.read(name);
Arguments:
1. name - (string) The name of the Cookie to retrieve.
Returns:
Examples:
Cookie.read("username");
Syntax:
var oldCookie = Cookie.dispose(cookie[, options]);
Arguments:
1. name - (string) The name of the cookie to remove or a previously saved Cookie instance. 2. options - (object, optional) See Cookie.
Examples:
Remove a Cookie:
Cookie.dispose('username'); //Bye-bye JackBauer! Seeya in 24 Hours.
133
134
Class: Swiff
Creates and returns a Flash object using supplied parameters.
Credits:
Flash detection and Internet Explorer/Flash Player 9 fix adapted from SWFObject.
Syntax:
var mySwiff = new Swiff(path[, options]);
Arguments:
1. path - (string) The path to the SWF file. 2. options - (object, optional) See Options below.
Options:
id - (string: defaults to 'Swiff_' + unique id) The id of the SWF object. width - (number: defaults to 1) The width of the SWF object. height - (number: defaults to 1) The height of the SWF object. container - (element) The container into which the SWF object will be injected. params - (object) Parameters to be passed to the SWF object (wmode, bgcolor, allowScriptAccess, loop, etc.). allowScriptAccess - (string: defaults to always) The domain that the SWF object allows access to. quality - (string: defaults to 'high') The render quality of the movie. swLiveConnect - (boolean: defaults to true) the swLiveConnect parameter to allow remote scripting. wMode - (string: defaults to 'transparent') Allows the SWF to be displayed with a transparent background. properties - (object) Additional attributes for the object element. vars - (object) Vars will be passed to the SWF as querystring in flashVars. events - (object) Functions to call from the SWF. These will be available globally in the movie, and bound to the object.
Returns:
135
Example:
var obj = new Swiff('myMovie.swf', { id: 'myBeautifulMovie' width: 500, height: 400, params: { wmode: 'opaque', bgcolor: '#ff3300' }, vars: { myVariable: myJsVar, myVariableString: 'hello' }, events: { onLoad: myOnloadFunc } });
Note:
1. Although Swiff returns the object, this element will NOT have any Element methods applied to it. 2. The $ function on an object/embed tag will only return its reference without further processing.
Syntax:
var result = Swiff.remote(obj, fn);
Arguments:
1. obj - (element) A Swiff instance (an HTML object Element). 2. fn - (string) The name of the function to execute in the Flash movie.
Returns:
Example:
var obj = new Swiff('myMovie.swf'); //Alerts "This is from the .swf file!". alert(Swiff.remote(obj, 'myFlashFn'));
Note:
The SWF file must be compiled with the ExternalInterface component. See the Adobe documentation on External Interface for more information.
136
Class: Fx
This Class will rarely be used on its own, but provides the foundation for all custom Fx Classes. All of the other Fx Classes inherit from this one.
Implements:
Fx Method: constructor
Syntax:
var myFx = new Fx([options]);
Arguments:
1. options - (object, optional) An object with options for the effect. See below.
Options:
fps - (number: defaults to 50) The frames per second for the transition. unit - (string: defaults to false) The unit, e.g. 'px', 'em', or '%'. See Element:setStyle. link - (string: defaults to ignore) Can be 'ignore', 'cancel' and 'link'. 'ignore' - Any calls made to start while the effect is running will be ignored. (Synonymous with 'wait': true from 1.x) 'cancel' - Any calls made to start while the effect is running will take precedence over the currently running transition. The new transition will start immediately, canceling the one that is currently running. (Synonymous with 'wait': false from 1.x) 'chain' - Any calls made to start while the effect is running will be chained up, and will take place as soon as the current effect has finished, one after another. duration - (number: defaults to 500) The duration of the effect in ms. Can also be one of: 'short' - 250ms 'normal' - 500ms 'long' - 1000ms transition - (function: defaults to Fx.Transitions.Sine.easeInOut The equation to use for the effect see Fx.Transitions. Also accepts a string in the following form: transition[:in][:out] - for example, 'linear', 'quad:in', 'back:in', 'bounce:out', 'elastic:out', 'sine:in:out'
Events:
onStart - (function) The function to execute when the effect begins. onCancel - (function) The function to execute when you manually stop the effect. onComplete - (function) The function to execute after the effect has processed. onChainComplete - (function) The function to execute when using link 'chain' (see options). It gets called after all effects in the chain have completed.
137
Notes:
You cannot change the transition if you haven't included Fx.Transitions.js, (unless you plan on developing your own curve). ;) The Fx Class is just a skeleton for other Classes to extend the basic functionality.
See Also:
Fx.Tween, Fx.Morph.
Fx Method: start
The start method is used to begin a transition. Fires the onStart event.
Syntax:
myFx.start(from[, to]);
Arguments:
1. from - (mixed) The starting value for the effect. If only one argument is provided, this value will be used as the target value. 2. to - (mixed, optional) The target value for the effect.
Returns:
Examples:
Notes:
If only one parameter is provided, the first argument to start will be used as the target value, and the initial value will be calculated from the current state of the element. The format and type of this value will be dependent upon implementation, and may vary greatly on a case by case basis. Check each implementation for more details.
Fx Method: set
The set method is fired on every step of a transition. It can also be called manually to set a specific value to be immediately applied to the effect.
Syntax:
myFx.set(value);
138
Arguments:
1. value - (mixed) The value to immediately apply to the transition.
Returns:
Examples:
Fx Method: cancel
The cancel method is used to cancel a running transition. Fires the onCancel event.
Syntax:
myFx.cancel();
Returns:
Fx Method: pause
Temporarily pause a currently running effect.
Syntax:
myFx.pause();
Returns:
Notes:
The timer will be stopped to allow the effect to continue where it left off by calling Fx:resume. If you call start on a paused effect, the timer will simply be cleared allowing the new transition to start.
Fx Method: resume
Resume a previously paused effect.
139
Syntax:
myFx.resume();
Returns:
Notes:
The effect will only be resumed if it has been previously paused. Otherwise, the call to resume will be ignored.
140
Class: Fx.CSS
CSS parsing class for effects. Required by Fx.Tween, Fx.Morph, Fx.Elements. Has no public methods.
141
Class: Fx.Tween
Contains Fx.Tween and the Element shortcut Element.tween.
Extends:
Fx
Syntax:
var myFx = new Fx.Tween(element, [, options]);
Arguments:
1. element - (mixed) An Element or the string id of an Element to apply the transition to. 2. options - (object, optional) The options object, plus the options described below:
Options:
property - (string) The CSS property to transition to, for example 'width', 'color', 'font-size', 'border', etc. If this option is omitted, you are required to use the property as a first argument for the start and set methods. Defaults to null.
Notes:
Any CSS property that can be set with Element:setStyle can be transitioned with Fx.Tween. If a property is not mathematically calculable, like border-style or background-image, it will be set immediately upon start of the transition. If you use the property option, you must not use the property argument in the start and set methods.
See Also:
Fx
Syntax:
myFx.set(property, value);
142
Arguments:
1. property - (string) The css property to set the value to. Omit this if you use the property option. 2. value - (mixed) The value to set the CSS property of this instance to.
Returns:
Examples:
var myFx = new Fx.Tween(element); //Immediately sets the background color of the element to red: myFx.set('background-color', '#f00');
Note:
If you use the property option, you must not use the property argument in the start and set methods.
Syntax:
myFx.start([property], from[, to]);
Arguments:
1. property - (string, if not in options) The css property to tween. Omit this if you use the property option. 2. from - (mixed) The starting CSS property value for the effect. If only one argument is provided, this value will be used as the target value. 3. to - (mixed, optional) The target CSS property value for the effect.
Returns:
Examples:
var myFx = new Fx.Tween(element); //Transitions the background color of the Element from black to red: myFx.start('background-color', '#000', '#f00'); //Transitions the background color of the Element from its current color to blue: myFx.start('background-color', '#00f');
143
Notes:
If only one argument is provided, other than the property argument, the first argument to start will be used as the target value, and the initial value will be calculated from the current state of the element. When using colors, either RGB or Hex values may be used. If you use the property option, you must not use the property argument in the start and set methods.
144
Hash: Element.Properties
see Element.Properties
Setter:
Syntax:
el.set('tween'[, options]);
Arguments:
Returns:
Examples:
el.set('tween', {duration: 'long'}); el.tween('color', '#f00');
Getter:
Syntax:
el.get('tween', [options]);
Arguments: 1. property - (string) the Fx.Tween property argument. 2. options - (object) the Fx.Tween options. Returns:
Examples:
el.get('tween', {property: 'opacity', duration: 'long'}).start(0);
145
Notes:
When initializing the Element's tween instance with Element:set, the property to tween SHOULD NOT be passed. The property must be specified when using Element:get to retrieve the actual Fx.Tween instance, and in calls to Element:tween. When options are passed to either the setter or the getter, the instance will be recreated. As with the other Element shortcuts, the difference between a setter and a getter is that the getter returns the instance, while the setter returns the element (for chaining and initialization).
146
Native: Element
Custom Native to allow all of its methods to be used with any DOM element via the dollar function $.
Syntax:
myElement.tween(property, startvalue[, endvalue]);
Arguments:
1. property - (string) the css property you want to animate. Omit this if you previously set the property option. 2. startvalue - (mixed) The start value for the transition. 3. endvalue - (mixed) The end value for the transition. If this is omitted, startvalue will be used as endvalue.
Returns:
Examples:
//Transitions the width of "myElement" from its current width to 100px: $('myElement').tween('width', '100'); //Transitions the height of "myElement" from 20px to 200px: $('myElement').tween('height', [20, 200]); //Transitions the border of "myElement" from its current to "6px solid blue": $('myElement').tween('border', '6px solid #36f');
See Also:
Fx.Tween
Syntax:
myElement.fade([how]);
147
Arguments:
1. how - (mixed, optional: defaults to 'toggle') The opacity level as a number or string representation. Possible values include: 'in' - Fade the element to 100% opacity. 'out' - Fade the element to 0% opacity. 'show' - Immediately set the element's opacity to 100%. 'hide' - Immediately set the element's opacity to 0%. 'toggle' - If visible, fade the element out, otherwise, fade it in. (number) - A float value between 0 and 1. Will fade the element to this opacity.
Returns:
This Element.
Examples:
$('myElement').fade('out'); //Fades "myElement" out. $('myElement').fade(0.7); //Fades "myElement" to 70% opacity.
Syntax:
myElement.highlight([start, end]);
Arguments:
1. start - (string, optional: defaults to '#ff8') The color from which to start the transition. 2. end - (string, optional: defaults to Element's set background-color) The background color to return to after the highlight effect.
Note:
If no background color is set on the Element, or its background color is set to 'transparent', the default end value will be white.
Returns:
148
Examples:
//Will immediately change the background to light blue, then back to its original color (or white): $('myElement').highlight('#ddf'); //Will immediately change the background to light blue, then fade to grey: $('myElement').highlight('#ddf', '#ccc');
149
Class: Fx.Morph
Allows for the animation of multiple CSS properties at once, even by a CSS selector. Inherits methods, properties, options and events from Fx.
Extends:
Fx
Syntax:
var myFx = new Fx.Morph(element[, options]);
Arguments:
1. element - (mixed) A string ID of the Element or an Element to apply the style transitions to. 2. options - (object, optional) The Fx options object.
Returns:
Examples:
Multiple styles with start and end values using an object:
var myEffect = new Fx.Morph('myElement', {duration: 'long', transition: Fx.Transitions.Sine.easeOut}); myEffect.start({ 'height': [10, 100], //Morphs the 'height' style from 10px to 100px. 'width': [900, 300] //Morphs the 'width' style from 900px to 300px. });
Multiple styles with the start value omitted will default to the current Element's value:
var myEffect = new Fx.Morph('myElement', {duration: 'short', transition: Fx.Transitions.Sine.easeOut}); myEffect.start({ 'height': 100, //Morphs the height from the current to 100px. 'width': 300 //Morphs the width from the current to 300px. });
Morphing one Element to match the CSS values within a CSS class:
var myEffect = new Fx.Morph('myElement', {duration: 1000, transition: Fx.Transitions.Sine.easeOut}); //The styles of myClassName will be applied to the target Element. myEffect.start('.myClassName');
150
See Also:
Fx
Syntax:
myFx.set(to);
Arguments:
1. properties - (mixed) Either an object of key/value pairs of CSS attributes to change or a string representing a CSS selector which can be found within the CSS of the page. If only one value is given for any CSS property, the transition will be from the current value of that property to the value given.
Returns:
Examples:
var myFx = new Fx.Morph('myElement').set({ 'height': 200, 'width': 200, 'background-color': '#f00', 'opacity': 0 }); var myFx = new Fx.Morph('myElement').set('.myClass');
Syntax:
myFx.start(to);
Arguments:
1. properties - (mixed) An object of key/value pairs of CSS attributes to change or a string representing a CSS selector which can be found within the CSS of the page. If only one value is given for any CSS property, the transition will be from the current value of that property to the value given.
Returns:
Examples:
var myEffects = new Fx.Morph('myElement', {duration: 1000, transition: Fx.Transitions.Sine.easeOut}); myEffects.start({ 'height': [10, 100], 'width': [900, 300], 'opacity': 0, 'background-color': '#00f' });
Notes:
If a string is passed as the CSS selector, the selector must be identical to the one within the CSS. Multiple selectors (with commas) are not supported.
152
Hash: Element.Properties
see Element.Properties
Examples:
el.set('morph', {duration: 'long', transition: 'bounce:out'}); el.morph({height: 100, width: 100});
Getter
Gets the default Fx.Morph instance for the Element. Syntax:
el.get('morph');
Arguments: 1. options - (object, optional) The Fx.Morph options. If these are passed in, a new instance will be generated. Returns:
153
Examples:
el.set('morph', {duration: 'long', transition: 'bounce:out'}); el.morph({height: 100, width: 100}); el.get('morph'); //The Fx.Morph instance.
154
Native: Element
Element Method: morph
Animates an Element given the properties passed in.
Syntax:
myElement.morph(properties);
Arguments:
1. properties - (mixed) The CSS properties to animate. Can be either an object of CSS properties or a string representing a CSS selector. If only one value is given for any CSS property, the transition will be from the current value of that property to the value given.
Returns:
Example:
With an object:
$('myElement').morph({height: 100, width: 200});
With a selector:
$('myElement').morph('.class1');
See Also:
Fx.Morph
155
Class: Fx
Fx.Transitions overrides the base Fx constructor, and adds the possibility to use the transition option as string.
Transition option:
The equation to use for the effect. See Fx.Transitions. It accepts both a function (ex: Fx.Transitions.Sine.easeIn) or a string ('sine:in', 'bounce:out' or 'quad:in:out') that will map to Fx.Transitions.Sine.easeIn / Fx.Transitions.Bounce.easeOut / Fx.Transitions.Quad.easeInOut
156
Hash: Fx.Transitions
A collection of tweening transitions for use with the Fx classes.
Examples:
//Elastic.easeOut with default values: var myFx = $('myElement').effect('margin', {transition: Fx.Transitions.Elastic.easeOut});
See also:
Note:
157
158
Class: Fx.Transition
This class is only useful for math geniuses who want to write their own easing equations. Returns an Fx transition function with 'easeIn', 'easeOut', and 'easeInOut' methods.
Syntax:
var myTransition = new Fx.Transition(transition[, params]);
Arguments:
1. transition - (function) Can be a function or a user-provided function which will be extended with easing functions. 2. params - (mixed, optional) Single value or an array for multiple values to pass as the second parameter for the transition function.
Returns:
Examples:
//Elastic.easeOut with user-defined value for elasticity. var myTransition = new Fx.Transition(Fx.Transitions.Elastic, 3); var myFx = $('myElement').effect('margin', {transition: myTransition.easeOut});
See Also:
Fx.Transitions
159
Class: Request
An XMLHttpRequest Wrapper.
Implements:
Chain, Events, Options
Syntax:
var myRequest = new Request([options]);
Arguments:
1. options - (object, optional) See below.
Options:
url - (string: defaults to null) The URL to request. method - (string: defaults to 'post') The HTTP method for the request, can be either 'post' or 'get'. data - (string: defaults to '') The default data for Request:send, used when no data is given. async - (boolean: defaults to true) If set to false, the requests will be synchronous and freeze the browser during request. encoding - (string: defaults to "utf-8") The encoding to be set in the request header. autoCancel - (boolean: defaults to false) When set to true, automatically cancels the already running request if another one is sent. Otherwise, ignores any new calls while a request is in progress. headers - (object) An object to use in order to set the request headers. isSuccess - (function) Overrides the built-in isSuccess function.
onSuccess
(function) Function to execute when the Request completes.
160
Signature:
onSuccess(responseText, responseXML)
Arguments: 1. responseText - (string) The returned text from the request. 2. responseXML - (mixed) The response XML from the request.
onFailure
(function) Function to execute when the request fails (error status code). Signature:
onFailure(instance)
onException
(function) Function to execute when setting a request header fails. Signature:
onException(headerName, value)
Arguments: 1. headerName - (string) The name of the failing header. 2. value - (string) The value of the failing header.
onCancel
(function) Function to execute when a request has been cancelled. Signature:
onCancel()
Properties:
running - (boolean) True if the request is running. response - (object) Object with text and XML as keys. You can access this property in the onSuccess event.
161
Returns:
Example:
var myRequest = new Request({method: 'get', url: 'http://site.com/requestHandler.php'}).send('name=john&lastname=dorian');
See Also:
Wikipedia: XMLHttpRequest
Syntax:
myRequest.setHeader(name, value);
Arguments:
1. name - (string) The name for the header. 2. value - (string) The value to be assigned.
Returns:
Example:
var myRequest = new Request({url: 'getData.php', method: 'get', headers: {'X-Request': 'JSON'}}); myRequest.setHeader('Last-Modified','Sat, 1 Jan 2005 05:00:00 GMT');
Syntax:
myRequest.getHeader(name);
Arguments:
1. name - (string) The name of the header to retrieve the value of. 162
Returns:
(string) The value of the retrieved header. (null) null if the header is not found.
Example:
var myRequest = new Request(url, {method: 'get', headers: {'X-Request': 'JSON'}}); var headers = myRequest.getHeader('X-Request'); //Returns 'JSON'.
Syntax:
myRequest.send([options]);
Arguments:
1. options - (object, optional) The options for the sent Request. Will also accept data as a query string for compatibility reasons.
Returns:
Examples:
var myRequest = new Request({url: 'http://localhost/some_url'}).send("save=username&name=John");
Syntax:
myRequest.cancel();
Returns:
163
Example:
var myRequest = new Request({url: 'mypage.html', method: 'get'}).send('some=data'); myRequest.cancel();
164
Hash: Element.Properties
see Element.Properties
Example:
myForm.set('send', {url: 'contact.php', method: 'get'}); myForm.send(); //Sends the form.
Getter
Returns the previously set Request instance (or a new one with default options). Syntax:
el.get('send'[, options]);
Arguments: 1. options - (object, optional) The Request options. If passed, this method will generate a new instance of the Request class.
Returns:
165
Example:
el.get('send', {method: 'get'}); el.send(); el.get('send'); //Returns the Request instance.
166
Native: Element
Custom Native to allow all of its methods to be used with any DOM element via the dollar function $.
Syntax:
myElement.send(url);
Arguments:
1. url - (string, optional) The url you want to send the form or the "container of inputs" to. If url is omitted, the action of the form will be used. url cannot be omitted for "container of inputs".
Returns:
Example:
HTML
<form id="myForm" action="submit.php"> <p> <input name="email" value="bob@bob.com"> <input name="zipCode" value="90210"> </p> </form>
JavaScript
$('myForm').send();
Note:
167
Class: Request.HTML
Request Specifically made for receiving HTML.
Extends:
Request
Syntax:
var myHTMLRequest = new Request.HTML([options]);
Arguments:
1. url - (string, optional) The URL pointing to the server-side script. 2. options - (object, optional) See options below. Also inherited are all the options from Request.
Options:
url - (string: defaults to null) The URL to load. This can also be passed within the .get() and .post() methods. update - (element: defaults to null) The Element to insert the response text of the Request into upon completion of the request. evalScripts - (boolean: defaults to true) If set to true, script tags inside the response will be evaluated. evalResponse - (boolean: defaults to false) If set to true, the entire response will be evaluated.
Events:
onComplete
Signature:
onComplete(responseTree, responseElements, responseHTML, responseJavaScript)
Arguments:
1. 2. 3. 4.
responseTree - (element) The node list of the remote response. responseElements - (array) An array containing all elements of the remote response. responseHTML - (string) The content of the remote response. responseJavaScript - (string) The portion of JavaScript from the remote response.
Returns:
168
Examples:
Simple GET Request:
var myHTMLRequest = new Request.HTML().get('myPage.html');
JavaScript
//Needs to be in a submit event or the form handler. var myHTMLRequest = new Request.HTML({url:'save/'}).post($('user-form'));
See Also:
Request
169
Hash: Element.Properties
see Element.Properties
Example:
el.set('load', {evalScripts: true}); el.load('some/request/uri');
Getter
Returns either the previously set Request.HTML instance or a new one with default options. Syntax:
el.get('load', options);
Arguments: 1. options - (*object, optional) The Request.HTML options. If these are passed in, a new instance will be generated, regardless of whether or not one is set. Returns:
170
Example:
el.set('load', {method: 'get'}); el.load('test.html'); //The getter returns the Request.HTML instance, making its class methods available. el.get('load').post('http://localhost/script');
171
Native: Element
Custom Native to allow all of its methods to be used with any DOM element via the dollar function $.
Syntax:
myElement.load(url);
Arguments:
1. url - (string) The URL pointing to the server-side document.
Returns:
Example:
HTML
<div id="content">Loading content...</div>
JavaScript
$('content').load('page_1.html');
172
Class: Request.JSON
Wrapped Request with automated sending and receiving of JavaScript Objects in JSON Format.
Extends:
Request
Syntax:
var myJSONRemote = new Request.JSON([options]);
Arguments:
1. options - (object, optional) See below.
Options:
secure - (boolean: defaults to true) If set to true, a syntax check will be done on the result JSON (see ).
Events:
Arguments: 1. responseJSON - (object) The JSON response object from the remote request. 2. text - (string) The JSON response as string. Returns:
Example:
//This code will send a data object via a GET request and alert the retrieved data. var jsonRequest = new Request.JSON({url: "http://site.com/tellMeAge.php", onComplete: function(person){ alert(person.age); //Alerts "25 years". alert(person.height); //Alerts "170 cm". alert(person.weight); //Alerts "120 kg". }}).get({'firstName': 'John', 'lastName': 'Doe'});
173
Class: Fx.Slide
The slide effect slides an Element in horizontally or vertically. The contents will fold inside.
Note:
Extends:
Fx
Syntax:
var myFx = new Fx.Slide(element[, options]);
Arguments:
1. elements - (element) The element to slide. 2. options - (object, optional) All of Fx options in addition to mode and wrapper. Options 1. mode - (string: defaults to 'vertical') String to indicate what type of sliding. Can be set to 'vertical' or 'horizontal'. 2. wrapper - (element: defaults to this.element) Allows to set another Element as wrapper. Properties: 1. open - (boolean) Indicates whether the slide element is visible.
Examples:
//Hides the Element, then brings it back in with toggle and finally alerts //when complete: var mySlide = new Fx.Slide('container').hide().toggle().chain(function(){ alert(mySlide.open); //Alerts true. });
Notes:
To create the slide effect an additional Element (a "div" by default) is wrapped around the given Element. This wrapper adapts the margin from the Element.
174
Syntax:
myFx.slideIn([mode]);
Arguments:
1. mode - (string, optional) Override the passed in Fx.Slide option with 'horizontal' or 'vertical'.
Returns:
Examples:
var myFx = new Fx.Slide('myElement').slideOut().chain(function(){ this.show().slideIn('horizontal'); });
Syntax:
myFx.slideOut([mode]);
Arguments:
1. mode - (string, optional) Override the passed in Fx.Slide option with 'horizontal' or 'vertical'.
Returns:
Examples:
var myFx = new Fx.Slide('myElement', { mode: 'horizontal', //Due to inheritance, all the [Fx][] options are available. onComplete: function(){ alert('Poof!'); } //The mode argument provided to slideOut overrides the option set. }).slideOut('vertical');
Syntax:
myFx.toggle([mode]);
Arguments:
1. mode - (string, optional) Override the passed in Fx.Slide option with 'horizontal' or 'vertical'.
Returns:
Examples:
var myFx = new Fx.Slide('myElement', { duration: 1000, transition: Fx.Transitions.Pow.easeOut }); //Toggles between slideIn and slideOut twice: myFx.toggle().chain(myFx.toggle);
Syntax:
myFx.hide([mode]);
Arguments:
1. mode - (string, optional) Override the passed in Fx.Slide option with 'horizontal' or 'vertical'.
Returns:
Examples:
var myFx = new Fx.Slide('myElement', { duration: 'long', transition: Fx.Transitions.Bounce.easeOut }); //Automatically hides and then slies in "myElement": myFx.hide().slideIn();
176
Syntax:
myFx.show([mode]);
Arguments:
1. mode - (string, optional) Override the passed in Fx.Slide option with 'horizontal' or 'vertical'.
Returns:
Examples:
var myFx = new Fx.Slide('myElement', { duration: 1000, transition: Fx.Transitions.Bounce.easeOut }); //Slides "myElement" out. myFx.slideOut().chain(function(){ //Waits one second, then the Element appears without transition. this.show.delay(1000, this); });
177
Hash: Element.Properties
See Element.Properties.
Syntax:
el.set('slide'[, options]);
Arguments:
1. options - (object) the Fx.Morph options.
Returns:
Example:
el.set('slide', {duration: 'long', transition: 'bounce:out'}); el.slide('in');
Syntax:
el.get('slide');
Arguments:
1. options - (object, optional) the Fx.Slide options. if passed in will generate a new instance.
Returns:
Examples:
el.set('slide', {duration: 'long', transition: 'bounce:out'}); el.slide('in'); el.get('slide'); //the Fx.Slide instance
178
Native: Element
Custom Native to allow all of its methods to be used with any DOM element via the dollar function $.
Syntax:
myElement.slide(how);
Arguments:
1. how - (string, optional) Can be 'in', 'out', 'toggle', 'show' and 'hide'. Defaults to 'toggle'.
Returns:
Examples:
$('myElement').slide('hide').slide('in');
179
Class: Fx.Scroll
Scrolls any element with an overflow, including the window element.
Note:
Extends:
Fx
Arguments:
1. element - (mixed) A string of the id for an Element or an Element reference to scroll. 2. options - (object, optional) All Fx Options in addition to offset, overflown, and wheelStops. Options: 1. offset - (object: defaults to {'x': 0, 'y': 0}) An object with x and y properties of the distance to scroll to within the Element. 2. overflown - (array: defaults to []) An array of nested scrolling containers, see Element:getPosition for an explanation. 3. wheelStops - (boolean: defaults to true) If false, the mouse wheel will not stop the transition from happening.
Returns:
Examples:
var myFx = new Fx.Scroll('myElement', { offset: { 'x': 0, 'y': 100 } }).toTop();
180
Notes:
Fx.Scroll transition will stop on mousewheel movement if the wheelStops option is not set to false. This is to allow users to control their web experience. Fx.Scroll is useless for Elements without scrollbars.
Syntax:
myFx.set(x, y);
Arguments:
1. x - (integer) The x coordinate to scroll the Element to. 2. y - (integer) The y coordinate to scroll the Element to.
Returns:
Examples:
var myElement = $(document.body); var myFx = new Fx.Scroll(myElement).set(0, 0.5 * document.body.offsetHeight);
Syntax:
myFx.start(x, y);
Arguments:
1. x - (integer) The x coordinate to scroll the Element to. 2. y - (integer) The y coordinate to scroll the Element to.
Returns:
181
Examples:
var myElement = $(document.body); var myFx = new Fx.Scroll(myElement).start(0, 0.5 * document.body.offsetHeight);
Notes:
Syntax:
myFx.toTop();
Returns:
Examples:
//Scrolls "myElement" 200 pixels down from its top and, after 1.5 seconds, //back to the top. var myFx = new Fx.Scroll('myElement', { onComplete: function(){ this.toTop.delay(1500, this); } }).scrollTo(0, 200).chain(function(){ this.scrollTo(200, 0); });
Syntax:
myFx.toBottom();
Returns:
182
Examples:
//Scrolls the window to the bottom and, after one second, to the top. var myFx = new Fx.Scroll(window).toBottom().chain(function(){ this.toTop.delay(1000, this); });
Syntax:
myFx.toLeft();
Returns:
Examples:
//Scrolls "myElement" 200 pixels to the right and then back. var myFx = new Fx.Scroll('myElement').scrollTo(200, 0).chain(function(){ this.toLeft(); });
Syntax:
myFx.toRight();
Returns:
Examples:
//Scrolls "myElement" to the right edge and then to the bottom. var myFx = new Fx.Scroll('myElement', { duration: 5000, wait: false }).toRight(); myFx.toBottom.delay(2000, myFx);
183
Syntax:
myFx.toElement(el);
Arguments:
1. el - (mixed) A string of the Element's id or an Element reference to scroll to.
Returns:
Examples:
//Scrolls the "myElement" to the top left corner of the window. var myFx = new Fx.Scroll(window).toElement('myElement');
Notes:
184
Class: Fx.Elements
Fx.Elements allows you to apply any number of styles transitions to a collection of Elements.
Extends:
Fx
Syntax:
new Fx.Elements(elements[, options]);
Arguments:
1. elements - (array) A collection of Elements the effects will be applied to. 2. options - (object, optional) Same as Fx options.
Returns:
Examples:
var myFx = new Fx.Elements($$('.myElementClass'), { onComplete: function(){ alert('complete'); } }).start({ '0': { 'height': [200, 300], 'opacity': [0,1] }, '1': { 'width': [200, 300], 'opacity': [1,0] } });
Notes:
Syntax:
myFx.set(to);
185
Arguments:
1. to - (object) An object where each item in the collection is refered to as a numerical string ("1" for instance). The first item is "0", the second "1", etc.
Returns:
Examples:
var myFx = new Fx.Elements($$('.myClass')).set({ '0': { 'height': 200, 'opacity': 0 }, '1': { 'width': 300, 'opacity': 1 } });
Syntax:
myFx.start(obj);
Arguments:
1. obj - (object) An object where each item in the collection is refered to as a numerical string ("1" for instance). The first item is "0", the second "1", etc.
Returns:
Examples:
var myElementsEffects = new Fx.Elements($$('a')); myElementsEffects.start({ '0': { //let's change the first element's opacity and width 'opacity': [0,1], 'width': [100,200] }, '4': { //and the fifth one's opacity 'opacity': [0.2, 0.5] } });
186
Class: Drag
Enables the modification of two CSS properties of an Element based on the position of the mouse while the mouse button is down.
Implements:
Events, Chain
Arguments:
1. el - (element) The Element to apply the transformations to. 2. options - (object, optional) The options object.
Options:
grid - (integer: defaults to false) Distance in pixels for snap-to-grid dragging. handle - (element: defaults to the element passed in) The Element to act as the handle for the draggable element. invert - (boolean: defaults to false) Whether or not to invert the values reported on start and drag. limit - (object: defaults to false) An object with x and y properties used to limit the movement of the Element. modifiers - (object: defaults to {'x': 'left', 'y': 'top'}) An object with x and y properties used to indicate the CSS modifiers (i.e. 'left'). snap - (integer: defaults to 6) The distance to drag before the Element starts to respond to the drag. style - (boolean: defaults to true) Whether or not to set the modifier as a style property of the element. unit - (string: defaults to 'px') A string indicating the CSS unit to append to all integer values.
Events:
onBeforeStart - Executed before the Drag instance attaches the events. Receives the dragged element as an argument. onStart - Executed when the user starts to drag (on mousedown). Receives the dragged element as an argument. onSnap - Executed when the user has dragged past the snap option. Receives the dragged element as an argument. onDrag - Executed on every step of the drag. Receives the dragged element as an argument. onComplete - Executed when the user completes the drag. Receives the dragged element as an argument.
187
Examples:
var myDrag = new Drag('myDraggable', { snap: 0, onSnap: function(el){ el.addClass('dragging'); }, onComplete: function(el){ el.removeClass('dragging'); } }); //create an Adobe reader style drag to scroll container var myDragScroller = new Drag('myContainer', { style: false, invert: true, modifiers: {x: 'scrollLeft', y: 'scrollTop'} });
Notes:
See Also:
Syntax:
myDrag.attach();
Returns:
Examples:
var myDrag = new Drag('myElement').detach(); //The Element can't be dragged. $('myActivator').addEvent('click', function(){ alert('Ok, now you can drag.'); myDrag.attach(); });
See Also:
188
Syntax:
myDrag.detach();
Returns:
Examples:
var myDrag = new Drag('myElement'); $('myDeactivator').addEvent('click', function(){ alert('No more dragging for you, Mister.'); myDrag.detach(); });
See Also:
$, Element:makeDraggable, Element:addEvent
Syntax:
myDrag.stop();
Examples:
var myDrag = new Drag('myElement', { onSnap: function(){ this.moved = this.moved || 0; this.moved++; if(this.moved > 100) { this.stop(); alert("Stop! You'll make the Element angry."); } } });
189
Native: Element
Custom Native to allow all of its methods to be used with any DOM element via the dollar function $.
Syntax:
var myResize = myElement.makeResizable([options]);
Arguments:
1. options - (object, optional) See [Drag][] for acceptable options.
Returns:
Examples:
var myResize = $('myElement').makeResizable({ onComplete: function(){ alert('Done resizing.'); } });
See Also:
Drag
190
Class: Drag.Move
An extension to the base Drag class with additional functionality for dragging an Element. Supports snapping and droppables. Inherits methods, properties, options and events from Drag.
Note:
Drag.Move requires the page to be in Standards Mode.
Arguments:
1. el - (element) The Element to apply the drag to. 2. options - (object, optional) The options object. See below.
Options:
All the base Drag options, plus:
container - (element) If an Element is passed, drag will be limited to the passed Element's size and position. droppables - (array) The Elements that the draggable can drop into. Interaction with droppable work with events fired on the doppable element or, for 'emptydrop', on the dragged element. The Events 'over', 'leave' and 'drop' get fired on the droppable element with the dragged element as first argument when the dragged element hovers,leaves or get dropped on the droppable.
Events:
onDrop - Executed when the element drops. Passes as argument the element and the element dropped on. If dropped on nothing, the second argument is null. onLeave - Executed when the element leaves one of the droppables. onEnter - Executed when the element enters one of the droppables.
191
Example:
var myDrag = new Drag.Move('draggable', { droppables: '.droppable', onDrop: function(element, droppable){ if (!droppable) console.log(element, ' dropped on nothing'); else console.log(element, 'dropped on', droppable); }, onEnter: function(element, droppable){ console.log(element, 'entered', droppable); }, onLeave: function(element, droppable){ console.log(element, 'left', droppable); } });
Notes:
Drag.Move requires the page to be in Standards Mode. Drag.Move supports either position absolute or relative. If no position is found, absolute will be set.
Demos:
See Also:
Drag
Syntax:
myMove.stop();
192
Example:
var myElement = $('myElement').addEvent('emptydrop', function(){ alert('no drop occurred'); }); var myMove = new Drag.Move(myElement, { onSnap: function(){ // due to MooTool's inheritance, all [Drag][]'s Events are also available. this.moved = this.moved || 0; this.moved++; if(this.moved > 1000){ alert("You've gone far enough."); this.stop(); } } });
See Also:
Drag:stop
193
Native: Element
Custom Native to allow all of its methods to be used with any DOM element via the dollar function $.
Syntax:
var myDrag = myElement.makeDraggable([options]);
Arguments:
1. options - (object, optional) See Drag and Drag.Move for acceptable options.
Returns:
Example:
var myDrag = $('myElement').makeDraggable({ onComplete: function(){ alert('done dragging'); } });
See Also:
Drag, Drag.Move
194
Class: Color
Creates a new Color Class, which is an array with some color specific methods.
Syntax:
var myColor = new Color(color[, type]);
Arguments:
1. color - (mixed) A string or an array representation of a color. 2. type - (string, optional) A string representing the type of the color to create.
Color:
There are three typical representations of color: String, RGB, and HSB. For String representation see Element:setStyle for more information.
Examples:
String Representation:
'#fff'
Returns:
Examples:
var black = new Color('#000'); var purple = new Color([255,0,255]);
Notes:
195
Syntax:
var myMix = myColor.mix(color[, color2[, color3[, ...][, alpha]);
Arguments:
1. color - (mixed) A single or many colors, in hex or rgb representation, to mix with this Color. 2. alpha - (number, optional) If the last argument is a number, it will be treated as the amount of the color to mix.
Returns:
Examples:
// mix black with white and purple, each time at 10% of the new color var darkpurple = new Color('#000').mix('#fff', [255, 0, 255], 10); $('myDiv').setStyle('background-color', darkpurple);
Syntax:
var myInvert = myColor.invert();
Returns:
Examples:
var white = new Color('#fff'); var black = white.invert();
196
Syntax:
var hue = myColor.setHue(value);
Arguments:
1. value - (number) The hue to set.
Returns:
Example:
var myColor = new Color('#f00'); var myElement = $('myElement'); (function(){ myElement.setStyle('color', myColor.setHue(myColor.hsb[0]++))); }).periodical(250);
Syntax:
var saturate = myColor.setSaturation(percent);
Arguments:
1. percent - (number) The percentage of the saturation to set.
Returns:
Examples:
var myColor = new Color('#f00'); $('myElement').addEvent('mouseenter', function(){ this.setStyle('background-color', myColor.setSaturation(myColor.hsb[1]++)); });
Syntax:
var brighten = myColor.setBrightness(percent);
Arguments:
1. percent - (number) The percentage of the brightness to set.
Returns:
Examples:
var myColor = new Color('#000'); $('myElement').addEvent('mouseenter', function(){ this.setStyle('background-color', myColor.setBrightness(myColor.hsb[2]++)); });
Function: $RGB
Shortcut to create a new color, based on red, green, blue values.
Syntax:
var myColor = $RGB(r, g, b);
Arguments:
1. r - (number) A red value from 0 to 255. 2. g - (number) A green value from 0 to 255. 3. b - (number) A blue value from 0 to 255.
Returns:
Examples:
var myColor = $RGB($random(0,255), $random(0,255), $random(0,255));
Function: $HSB
Shortcut to create a new color, based on: hue, saturation, brightness values.
198
Syntax:
var myColor = $HSB(h, s, b);
Arguments:
1. h - (number) A hue value from 0 to 359. 2. s - (number) A saturation value from 0 to 100. 3. b - (number) A brightness value from 0 to 100.
Returns:
Examples:
var myColor = $HSB(50, 50, 100);
199
Native: Array
Contains Array prototypes.
See Also:
MDC Array
Syntax:
var myHSB = myRGBArray.rgbToHsb();
Returns:
Example:
var myHSB = [255, 0, 0].rgbToHsb(); //Returns [0, 100, 100].
Syntax:
var myHSB = myRGBArray.hsbToRgb();
Returns:
Examples:
var myRGB = [0, 100, 100].hsbToRgb(); //myRGB = [255, 0, 0]
200
Class: Group
This class is for grouping Classes or Events. The Event added to the Group will fire when all of the events of the items of the group are fired.
Syntax:
var myGroup = new Group(class[, arrays[, class2[, ... ]]]);
Arguments:
Any number of Class instances, or arrays containing class instances.
Returns:
Examples:
var xhr1 = new Ajax('data.js', {evalScript: true}); var xhr2 = new Ajax('abstraction.js', {evalScript: true}); var xhr3 = new Ajax('template.js', {evalScript: true}); var group = new Group(xhr1, xhr2, xhr3); group.addEvent('onComplete', function(){ alert('All Scripts loaded'); }); xhr1.request(); xhr2.request(); xhr3.request();
Syntax:
myGroup.addEvent(type, fn);
Arguments:
1. type - (string) The event name (e.g. 'onComplete') to add. 2. fn - (function) The callback function to execute when all instances fired this event.
Returns:
201
Examples:
var myElements = $('myForm').getElements('input, textarea, select'); myElements.addEvent('click', function(){ alert('an individual click'); }); var myGroup = new Group(myElements); myGroup.addEvent('click', function(){ alert('all form elements clicked'); });
202
Class: Hash.Cookie
Stores and loads a Hash as a Cookie using JSON format.
Extends:
Hash
Syntax:
var myHashCookie = new Hash.Cookie(name[, options]);
Arguments:
1. name - (string) The key (name) for the cookie 2. options - (object) All of Cookie options in addition an autoSave option. Options: 1. autoSave - (boolean: defaults to true) An option to save the cookie at every operation.
Returns:
Examples:
var fruits = new Hash.Cookie('myCookieName', {duration: 3600}); fruits.extend({ 'lemon': 'yellow', 'apple': 'red' }); fruits.set('melon', 'green'); fruits.get('lemon'); // yellow // ... on another page ... values load automatically var fruits = new Hash.Cookie('myCookieName', {duration: 365}); fruits.get('melon'); // green fruits.erase(); // delete cookie
Notes:
All Hash methods are available in your Hash.Cookie instance. if autoSave options is set, every method call will result in your Cookie being saved. Cookies have a limit of 4kb (4096 bytes). Therefore, be careful with your Hash size. All Hash methods used on Hash.Cookie return the return value of the Hash method, unless you exceeded the Cookie size limit. In that case the result will be false. If you plan to use large Cookies consider turning autoSave to off, and check the status of .save() everytime. Creating a new instance automatically loads the data from the Cookie into the Hash. Cool Huh? 203
See Also:
Hash
Syntax:
myHashCookie.save();
Returns:
(boolean) Returns false when the JSON string cookie is too long (4kb), otherwise true.
Examples:
var login = new Hash.Cookie('userstatus', {autoSave: false}); login.extend({ 'username': 'John', 'credentials': [4, 7, 9] }); login.set('last_message', 'User logged in!'); login.save(); // finally save the Hash
Syntax:
myHashCookie.load();
Returns:
Examples:
var myHashCookie = new Hash.Cookie('myCookie'); (function(){ myHashCookie.load(); if(!myHashCookie.length) alert('Cookie Monster must of eaten it!'); }).periodical(5000);
204
Notes:
205
Class: Sortables
Creates an interface for drag and drop sorting of a list or lists.
Arguments:
1. list - (mixed) required, the list or lists that will become sortable. This argument can be an Element, an array of Elements, or a selector. When a single list (or id) is passed, that list will be sortable only with itself. To enable sorting between lists, one or more lists or id's must be passed using an array or a selector. See Examples below. 2. options - (object) See options and events below. Options:
constrain - (boolean: defaults to false) Whether or not to constrain the element being dragged to its parent element. clone - (mixed: defaults to false) Whether or not to display a copy of the actual element under the cursor while dragging. May also be used as a function which will return an element to be used as the clone. The function will receive the mousedown event, the element, and the list as arguments. handle - (string: defaults to false) A selector to select an element inside each sortable item to be used as the handle for sorting that item. If no match is found, the element is used as its own handle. opacity - (integer: defaults to 1) Opacity of the place holding element revert - (mixed: defaults to false) Whether or not to use an effect to slide the element into its final location after sorting. If you pass an object it will be used as additional options for the revert effect. snap - (integer: defaults to 4) The number of pixels the element must be dragged for sorting to begin.
Events:
onStart - function executed when the item starts dragging onSort - function executed when the item is inserted into a new place in one of the lists onComplete - function executed when the item ends dragging
Examples:
var mySortables = new Sortables('list-1', { revert: { duration: 500, transition: 'elastic:out' } }); //creates a new Sortable instance over the list with id 'list-1' with some extra options for the revert effect var mySortables = new Sortables('#list-1, #list-2', { constrain: true, clone: false, revert: true }); //creates a new Sortable instance allowing the sorting of the lists with id's 'list-1' and 'list-2' with extra options //since constrain was set to true, the items will not be able to be dragged from one list to the other var mySortables = new Sortables('#list-1, #list-2, #list-3'); //creates a new Sortable instance allowing sorting between the lists with id's 'list-1', 'list-2, and 'list-3' (end)
206
Syntax:
mySortables.attach();
Returns:
Syntax:
mySortables.detach();
Returns:
Syntax:
mySortables.detach();
Returns:
Syntax:
mySortables.addItems(item1[, item2[, item3[, ...]]]);
207
Arguments:
1. items - (mixed) Since Array.flatten is used on the arguments, a single element, several elements, an array of elements, or any combination thereof may be passed to this method.
Returns:
Examples:
var mySortables = new Sortables('#list1, #list2'); var element1 = new Element('div'); var element2 = new Element('div'); var element3 = new Element('div'); $('list1').adopt(element1); $('list2').adopt(element2, element3); mySortables.addItems(element1, element2, element3);
Notes:
The items will not be injected into the list automatically as the sortable instance could have many lists. First inject the elements into the proper list, then call addItems on them.
See Also:
Sortables:removeItems, Sortables:addLists
Syntax:
mySortables.removeItems(item1[, item2[, item3[, ...]]]);
Arguments:
1. items - (mixed) Since Array.flatten is used on the arguments, a single element, several elements, an array of elements, or any combination thereof may be passed to this method.
Returns:
208
Examples:
var mySortables = new Sortables('#list1, #list2'); var element1 = $('list1').getFirst(); var element2 = $('list2').getLast(); mySortables.removeItems(element1, element2).destroy(); //the elements will be removed and destroyed
Notes:
The items will not be removed from the list automatically, they will just no longer be sortable. First call removeItems on the items, and then remove them from their list containers, or destroy them.
See Also:
Sortables:addItems, Sortables:removeLists
Syntax:
mySortables.addLists(list1[, list2[, list3[, ...]]]);
Arguments:
1. lists - (mixed) Since Array.flatten is used on the arguments, a single element, several elements, an array of elements, or any combination thereof may be passed to this method.
Returns:
Examples:
var mySortables = new Sortables('list1'); mySortables.addLists($('list2'));
Notes:
More complicated usage of this method will allow you to do things like one-directional sorting.
See Also:
Sortables:removeLists, Sortables:addItems
209
Syntax:
mySortables.removeLists(list1[, list2[, list3[, ...]]]);
Arguments:
1. lists - (mixed) Since Array.flatten is used on the arguments, a single element, several elements, an array of elements, or any combination thereof may be passed to this method.
Returns:
Examples:
var mySortables = new Sortables('#list1, #list2'); mySortables.removeLists($('list2'));
See Also:
Sortables:addLists, Sortables:removeItems
Arguments:
1. index - (mixed, optional) An integer or boolean false. index of the list to serialize. Omit or pass false to serialize all lists. 2. modifier - (function, optional) A function to override the default output of the sortables. See Examples below
210
Examples:
mySortables.serialize(1); //returns the second list serialized (remember, arrays are 0 based...); //['item_1-1', 'item_1-2', 'item_1-3'] mySortables.serialize(); //returns a nested array of all lists serialized, or if only one list exists, that lists order /*[['item_1-1', 'item_1-2', 'item_1-3'], ['item_2-1', 'item_2-2', 'item_2-3'], ['item_3-1', 'item_3-2', 'item_3-3']]*/ mySortables.serialize(2, function(element, index){ return element.getProperty('id').replace('item_','') + '=' + index; }).join('&'); //joins the array with a '&' to return a string of the formatted ids of all the elmements in list 3,with their position //'3-0=0&3-1=1&3-2=2'
211
Class: Tips
Display a tip on any element with a title and/or href.
Credits:
Note:
Implements:
Events, Options
elements - (mixed: optional) A collection of elements, a string Selector, or an Element to apply the tooltips to. options - (object) An object to customize this Tips instance.
Options:
showDelay - (number: defaults to 100) The delay the onShow method is called. hideDelay - (number: defaults to 100) The delay the onHide method is called. className - (string: defaults to null) the className your tooltip container will get. Useful for extreme styling. The tooltip element inside the tooltip container above will have 'tip' as classname. The title will have as classname: tip-title The text will have as classname: tip-text offsets - (object: defaults to {'x': 16, 'y': 16}) The distance of your tooltip from the mouse. fixed - (boolean: defaults to false) If set to true, the toolTip will not follow the mouse.
Events:
onHide: fires when the tip is shown onShow: fires when the tip is being hidden
Example:
HTML:
<a href="http://mootools.net" title="mootools homepage" class="thisisatooltip" />
212
JavaScript
var myTips = new Tips('.thisisatooltip');
(function) Fires when the Tip is starting to show and by default sets the tip visible.
Signature:
onShow(tip)
Arguments:
1. tip - (element) The tip element. Useful if you want to apply effects to it.
Example:
myTips.addEvent('onShow', function(tip){ tip.fade('in'); });
(function) Fires when the Tip is starting to hide and by default sets the tip hidden.
Signature:
onHide(tip)
Arguments:
1. tip - (element) The tip element. Useful if you want to apply effects to it.
Example:
myTips.addEvent('onHide', function(tip){ tip.fade('out'); });
213
Syntax:
myTips.attach(elements);
Arguments:
1. elements - (mixed) A collection of elements, a string Selector, or an Element to apply the tooltips to.
Returns:
Example:
myTips.attach('a.thisisatip');
Syntax:
myTips.detach(elements);
Arguments:
1. elements - (mixed) A collection of elements, a string Selector, or an Element to apply the tooltips to.
Returns:
Example:
myTips.detach('a.thisisatip');
214
Example:
HTML:
<a id="tip1" href="http://mootools.net" title="mootools homepage" class="thisisatooltip" />
JavaScript
$('tip1').store('tip:title', 'custom title for tip 1'); $('tip1').store('tip:text', 'custom text for tip 1');
Note:
If you use tips storage you can use elements and / or html as tips title and text.
215
Class: SmoothScroll
Auto targets all the anchors in a page and display a smooth scrolling effect upon clicking them.
Note:
Extends:
Fx.Scroll
Syntax:
var mySmoothScroll = new SmoothScroll([options[, win]]);
Arguments:
1. options - (object, optional) In addition to all the options, SmoothScroll has links option incase you had a predefined links collection. 2. win - (object, optional) The context of the SmoothScroll. Options:
links - (mixed) A collection of Elements or a string of Elements that the SmoothScroll can use.
Returns:
Examples:
var mySmoothScroll = new SmoothScroll({ links: '.smoothAnchors', wheelStops: false });
See Also:
Fx.Scroll
216
Class: Slider
Creates a slider with two elements: a knob and a container.
Note:
Syntax:
var mySlider = new Slider(element, knob[, options]);
Arguments:
1. element - (element) The knob element for the slider. 2. knob - (element) The handle element for the slider. 3. options - (object) An optional object for customizing the Slider. Options: 1. snap - (boolean: defaults to false) True if you want the knob to snap to the nearest value. 2. offset - (number: defaults to 0) Relative offset for knob position at start. 3. range - (mixed: defaults to false) Array of numbers or false. The minimum and maximum limits values the slider will use. 4. wheel - (boolean: defaults to false) True if you want the ability to move the knob by mousewheeling. 5. steps - (number: defaults to 100) The number of steps the Slider should move/tick. 6. mode - (string: defaults to horizontal) The type of Slider can be either 'horizontal' or 'vertical' in movement.
Notes:
Range option allows an array of numbers. Numbers can be negative and positive.
Signature:
onChange(step)
Arguments:
1. step - (number) The current step that the Slider is on.
217
Signature:
onComplete(step)
Arguments:
1. step - (string) The current step that the Slider is on as a string.
(function) Fires when the user drags the knob. This Event can be overriden to alter the onTick behavior.
Signature:
onTick(pos)
Arguments:
1. pos - (number) The current position that slider moved to.
Notes:
Slider originally uses the onTick event to set the style of the knob to a new position.
Returns:
Examples:
var mySlider = new Slider('myElement', 'myKnob', { range: [-50, 50], wheel: true, snap: true, onStart: function(){ this.borderFx = this.borderFx || this.element.tween('border').start('#ccc'); }, onTick: function(pos){ this.element.setStyle('border-color', '#f00'); this.knob.setStyle(this.p, pos); }, onComplete: function(){ this.element.tween('border').start('#000'); } });
218
Syntax:
mySlider.set(step);
Arguments:
1. step - (number) A number to position the Slider to.
Returns:
Examples:
var mySlider = new Slider('myElement', 'myKnob'); mySlider.set(0); var myPeriodical = (function(){ if(this.step == this.options.steps) $clear(myPeriodical); this.set(this.step++); }).periodical(1000, mySlider);
Notes:
Step will automatically be limited between 0 and the optional steps value.
219
Class: Scroller
The Scroller is a Class to scroll any element with an overflow (including the window) when the mouse cursor reaches certain buondaries of that element. You must call its start method to start listening to mouse movements.
Note:
Syntax:
new Scroller(element[, options]);
Implements:
Events, Options
Arguments:
1. element - (element) The element to scroll. 2. options - (object, optional) An object for the Scroller instance's options. Options :
area - (number: defaults to 20) The necessary boundaries to make the element scroll. velocity - (number: defaults to 1) The modifier for the window scrolling speed.
Events:
onChange - (function) When the mouse reaches some boundaries, you can choose to alter some other values, instead of the scrolling offsets.
Signature:
onChange(x, y);
220
Examples:
var myScroller = new Scroller(window, { area: Math.round(window.getWidth() / 5) }); (function(){ this.stop(); this.start(); }).periodical(1000, myScroller);
Syntax:
myScroller.start();
Examples:
var myScroller = new Scroller('myElement'); myScroller.start();
Syntax:
myScroller.start();
Examples:
var myElement = $('myElement'); var myScroller = new Scroller(myElement); myScroller.start(); myElement.addEvent('click', myScroller.stop.bind(myScroller)); //stop scrolling when the user clicks.
221
Hash: Assets
Provides methods for the dynamic loading and management of JavaScript, CSS, and image files.
Syntax:
var myScript = Asset.javascript(source[, properties]);
Arguments:
1. source - (string) The location of the JavaScript file to load. 2. properties - (object, optional) Additional attributes to be included into the script Element.
Returns:
Examples:
var myScript = new Asset.javascript('/scripts/myScript.js', {id: 'myScript'});
Syntax:
var myCSS = new Asset.css(source[, properties]);
Arguments:
1. source - (string) The path of the CSS file. 2. properties - (object) Some additional attributes you might want to add to the link Element.
Returns:
222
Examples:
var myCSS = new Asset.css('/css/myStyle.css', {id: 'myStyle', title: 'myStyle'});
Syntax:
var myImage = new Asset.image(source[, properties]);
Arguments:
1. source - (string) The path of the image file. 2. properties - (object) Some additional attributes you might want to add to the img Element including the onload/onerror/onabout events.
Returns:
Examples:
var myImage = new Asset.image('/images/myImage.png', {id: 'myImage', title: 'myImage', onload: myFunction});
Notes:
Does not inject the image into the page. WARNING: DO NOT use addEvent for load/error/abort on the returned element, give them as onload/onerror/onabort in the properties argument.
Syntax:
var myImages = new Asset.images(source[, options]);
Arguments:
1. sources - (mixed) An array or a string, of the paths of the image files. 2. options - (object, optional) See below.
223
Options:
onComplete
Signature:
onComplete()
onProgress
Signature:
onProgress(counter, index)
Arguments: 1. counter - (number) The number of loaded images. 2. index - (number) The index of the loaded image. Returns:
Examples:
var myImages = new Asset.images(['/images/myImage.png', '/images/myImage2.gif'], { onComplete: function(){ alert('All images loaded!'); } });
224
Class: Accordion
The Accordion class creates a group of Elements that are toggled when their handles are clicked. When one Element toggles into view, the others toggle out.
Notes:
Accordion requires the page to be in Standards Mode. Accordion elements will have their paddings and borders removed in order to make the transition display correctly. Best practice is to use the accordion elements as containers for elements that are styled exactly as you like.
Extends:
Fx.Elements
Syntax:
var myAccordion = new Accordion(togglers, elements[, options]);
Arguments:
1. togglers - (array) The collection of Elements which will be clickable and trigger the opening of sections of the Accordion. 2. elements - (array) The collection of Elements the transitions will be applied to. 3. options - (object, optional) All the Fx options in addition to options below. Options:
display - (integer: defaults to 0) The index of the element to show at start (with a transition). show - (integer: defaults to 0) The index of the element to be shown initially. height - (boolean: defaults to true) If set to true, a height transition effect will take place when switching between displayed elements. width - (boolean: defaults to false) If set to true, a width transition will take place when switching between displayed elements. opacity - (boolean: defaults to true) If set to true, an opacity transition effect will take place when switching between displayed elements. fixedHeight - (boolean: defaults to false) If set to false, displayed elements will have a fixed height. fixedWidth - (boolean: defaults to false) If set to true, displayed elements will have a fixed width. alwaysHide - (boolean: defaults to false) If set to true, it will be possible to close all displayable elements. Otherwise, one will remain open at all time. width - (boolean: defaults to false) If set to true, it will add a width transition to the accordion. Warning: css mastery is required to make this work!
Returns:
225
Events:
onActive
Signature:
onActive(toggler, element)
Arguments: 1. toggler - (element) The toggler for the Element being displayed. 2. element - (element) The Element being displayed.
onBackground
Signature:
onBackground(toggler, element)
Arguments: 1. toggler - (element) The toggler for the Element being displayed. 2. element - (element) The Element being displayed.
Examples:
var myAccordion = new Accordion($$('.togglers'), $$('.elements'), { display: 2, alwaysHide: true });
Demos:
Accordion - http://demos.mootools.net/Accordion
Syntax:
myAccordion.addSection(toggler, element[, pos]);
226
Arguments:
1. toggler - (element) The Element that toggles the Accordion section open. 2. element - (element) The Element that should stretch open when the toggler is clicked. 3. pos - (integer, optional) The index at which these objects are to be inserted within the Accordion (defaults to the end).
Returns:
Examples:
var myAccordion = new Accordion($$('.togglers'), $$('.elements')); myAccordion.addSection('myToggler1', 'myElement1'); // add the section at the end sections. myAccordion.addSection('myToggler2', 'myElement2', 0); //add the section at the beginning of the sections.
Syntax:
myAccordion.display(index);
Arguments:
1. index - (mixed) The index of the item to show, or the actual element to be displayed.
Returns:
Examples:
// Make a ticker-like accordion. Kids don't try this at home. var myAccordion = new Accordion('.togglers', '.elements', { onComplete: function(){ this.display.delay(2500, this, (this.previous + 1) % this.togglers.length); } });
227