Mootools操作实例文档

来源:互联网 发布:dota2天梯排名算法 编辑:程序博客网 时间:2024/05/01 05:20


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 andFunction:periodical.

Syntax:

$clear(timer);

Arguments:

1. timer - (number) The identifier of the setInterval (periodical) or setTimeout (delay) to clear.

Returns:

§ (null) returns null.

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

§ (function) A function which returns the desired value.

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.

Syntax:

$extend(original, extended);

Arguments:

1. original - (object) The object to be extended.

2. extension - (object) The object whose properties will be copied to original.

Returns:

§ (object) The first object passed in, extended.

Examples:

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 obj1 = {a: 0, b: 1};

var obj2 = {c: 2, d: 3};

var obj3 = {a: 4, d: 5};

var 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 seeFunction: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:

§ (mixed) Any number of variables.

Returns:

§ (mixed) The first variable that is defined.

§ (null) 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:

§ (number) A random number between min and max.

Example:

alert($random(520))//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:

§ (number) - The current timestamp.

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:

§ fn - (function) The function to execute.

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 uses the trident engine (e.g. Internet Explorer).

§ Browser.Engine.gecko - (boolean) True if the current browser uses the gecko engine (e.g. Firefox, or any Mozilla Browser).

§ Browser.Engine.webkit - (boolean) True if the current browser uses the webkit engine (e.g. Safari, Google Chrome, Konqueror).

§ Browser.Engine.presto - (boolean) True if the current browser uses the presto engine (e.g. Opera 9).

§ Browser.Engine.name - (string) The name of the engine.

§ Browser.Engine.version - (number) The version of the engine. (e.g. 950)

§ 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, Linux nor iPod.

§ Browser.Platform.name - (string) The name of the platform.

Notes:

§ Engine detection is entirely feature-based.

Native: Array

A collection of Array methods.

See Also:

§ MDC Array

Array Method: each

Calls a function for each element in the 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 seeFunction: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

Notes:

§ This method is only available for browsers without native MDC Array:forEach support.

Array Method: every

Returns true if every element in the array satisfies the provided testing function. This method is provided only for browsers without native Array:every 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 seeFunction: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 = [10425100].every(function(item, index){

    return item > 20;

})//areAllBigEnough = false

See Also:

§ MDC Array:every

Array Method: filter

Creates a new array with all of the elements of the array for which the provided filtering function returns true. This method is provided only for browsers without native Array:filtersupport.

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

§ (array) The new filtered array.

Examples:

var biggerThanTwenty = [10325100].filter(function(item, index){

    return item > 20;

})//biggerThanTwenty = [25, 100]

See Also:

§ MDC Array:filter

Array Method: clean

Creates a new array with all of the elements of the array which are defined (i.e. not null or undefined).

Syntax:

var cleanedArray = myArray.clean();

Returns:

§ (array) The new filtered array.

Examples:

var myArray = [null10truefalse"foo", undefined, ""];

myArray.clean() // returns [1, 0, true, false, "foo", ""]

Array Method: indexOf

Returns the index of the first element within the array equal to the specified value, or -1 if the value is not found. This method is provided only for browsers without native Array:indexOfsupport.

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

Array Method: map

Creates a new array with the results of calling a provided function on every element in the array. This method is provided only for browsers without native Array:map support.

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

§ (array) The new mapped array.

Examples:

var timesTwo = [123].map(function(item, index){

    return item * 2;

})//timesTwo = [2, 4, 6];

See Also:

§ MDC Array:map

Array Method: some

Returns true if at least one element in the array satisfies the provided testing function. This method is provided only for browsers without native Array:some support.

Syntax:

var somePassed = myArray.some(fn[, bind]);

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 seeFunction: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 = [10425100].some(function(item, index){

    return item > 20;

})//isAnyBigEnough = true

See Also:

§ MDC Array:some

Array Method: associate

Creates an object with key-value pairs based on the array of keywords passed in and the current content of the array.

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.

Returns:

§ (object) The new associated object.

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

Array Method: link

Accepts an object of key / function pairs to assign values.

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:

§ (object) The new associated object.

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}

Array Method: contains

Tests an array for the presence of an item.

Syntax:

var inArray = myArray.contains(item[, from]);

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

Array Method: extend

Extends an array with all the items of another.

Syntax:

myArray.extend(array);

Arguments:

1. array - (array) The array whose items should be extended into this array.

Returns:

§ (array) This array, extended.

Examples:

var animals = ['Cow''Pig''Dog'];

animals.extend(['Cat''Dog'])//animals = ['Cow', 'Pig', 'Dog', 'Cat', 'Dog'];

Array Method: getLast

Returns the last item from the array.

Syntax:

myArray.getLast();

Returns:

§ (mixed) The last item in this array.

§ (null) If this array is empty, returns null.

Examples:

['Cow''Pig''Dog''Cat'].getLast()//returns 'Cat'

Array Method: getRandom

Returns a random item from the array.

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

Array Method: include

Pushes the passed element into the array if it's not already present (case and type sensitive).

Syntax:

myArray.include(item);

Arguments:

1. item - (object) The item that should be added to this array.

Returns:

§ (array) This array with the new item included.

Examples:

['Cow''Pig''Dog'].include('Cat')//returns ['Cow', 'Pig', 'Dog', 'Cat']

['Cow''Pig''Dog'].include('Dog')//returns ['Cow', 'Pig', 'Dog']

Array Method: combine

Combines an array with all the items of another. Does not allow duplicates and is case and type sensitive.

Syntax:

myArray.combine(array);

Arguments:

1. array - (array) The array whose items should be combined into this array.

Returns:

§ (array) This array combined with the new items.

Examples:

var animals = ['Cow''Pig''Dog'];

animals.combine(['Cat''Dog'])//animals = ['Cow', 'Pig', 'Dog', 'Cat'];

Array Method: erase

Removes all occurrences of an item from the array.

Syntax:

myArray.erase(item);

Arguments:

1. item - (object) The item to search for in the array.

Returns:

§ (array) This array with all occurrences of the item removed.

Examples:

['Cow''Pig''Dog''Cat''Dog'].erase('Dog') //returns ['Cow', 'Pig', 'Cat']

['Cow''Pig''Dog'].erase('Cat') //returns ['Cow', 'Pig', 'Dog']

Array Method: empty

Empties an array.

Syntax:

myArray.empty();

Returns:

§ (array) This array, emptied.

Examples:

var myArray = ['old''data'];

myArray.empty()//myArray is now []

Array Method: flatten

Flattens a multidimensional array into a single array.

Syntax:

myArray.flatten();

Returns:

§ (array) A new flat array.

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]

Array Method: hexToRgb

Converts an hexidecimal color value to RGB. Input array must be the following hexidecimal color format. ['FF','FF','FF']

Syntax:

myArray.hexToRgb([array]);

Arguments:

1. array - (boolean, optional) If true is passed, will output an array (eg. [255, 51, 0]) instead of a string (eg. "rgb(255,51,0)").

Returns:

§ (string) A string representing the color in RGB.

§ (array) If the array flag is set, an array will be returned instead.

Examples:

['11','22','33'].hexToRgb()//returns "rgb(17,34,51)"

['11','22','33'].hexToRgb(true)//returns [17, 34, 51]

See Also:

§ String:hexToRgb

Array Method: rgbToHex

Converts an RGB color value to hexidecimal. Input array must be in one of the following RGB color formats. [255,255,255], or [255,255,255,1]

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

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:

§ (array) The new copied array.

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 = [01234];

var copiedArray = $A(anArray)//Returns [0, 1, 2, 3, 4].

Array

each

every

filter

clean

indexOf

map

some

associate

link

contains

extend

getLast

getRandom

include

combine

erase

empty

flatten

hexToRgb

rgbToHex

Utility

A

Native: Function

Function Methods.

See Also:

§ MDC Function

Function Method: create

Base function for creating functional closures which is used by all other Function prototypes.

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.

Example:

var myFunction = function(){

    alert("I'm a function. :D");

};

 

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

});

Function Method: pass

Returns a closure with arguments and bind.

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:

§ (function) The function whose arguments are passed when called.

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.

Function Method: attempt

Tries to execute the function.

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:

§ (mixed) The function's return value or null if an exception is thrown.

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

Function Method: bind

Changes the scope of this within the target function to refer to the bind parameter.

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:

§ (function) The bound function.

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.

Function Method: bindWithEvent

Changes the scope of this within the target function to refer to the bind parameter. It also makes "space" for an event. This allows the function to be used in conjunction withElement:addEvent and arguments.

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:

§ (function) The bound function.

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.

Function Method: delay

Delays the execution of a function by a specified duration.

Syntax:

var timeoutID = myFunction.delay([delay[, bind[, args]]]);

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:

§ (number) The JavaScript timeout id (for clearing delays).

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:

§ $clear, MDC setTimeout

Function Method: periodical

Executes a function in the specified intervals of time. Periodic execution can be stopped using the $clear function.

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:

§ (number) The Interval id (for clearing a periodical).

Example:

var Site = { counter: 0 };

var addCount = function(){ this.counter++; };

addCount.periodical(1000, Site)//Will add the number of seconds at the Site.

See Also:

§ $clear, MDC setInterval

Function Method: run

Runs the Function with specified arguments and binding. The same as apply but reversed and with support for a single argument.

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:

§ (mixed) This Function's return value.

Examples:

Simple Run:

var myFn = function(a, b, c){

    return a + b + c;

}

var myArgs = [1,2,3];

myFn.run(myArgs)//Returns: 6

Run With Binding:

var myFn = function(a, b, c) {

    return a + b + c + this;

}

var myArgs = [1,2,3];

myFn.run(myArgs, 6)//Returns: 12

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.

Number Method: limit

Limits this number between two bounds.

Syntax:

myNumber.limit(min, max);

Arguments:

1. min - (number) The minimum possible value.

2. max - (number) The maximum possible value.

Returns:

§ (number) The number bounded between the given limits.

Examples:

(12).limit(26.5);  //Returns: 6.5

(-4).limit(26.5);  //Returns: 2

(4.3).limit(26.5)//Returns: 4.3

Number Method: round

Returns this number rounded to the specified precision.

Syntax:

myNumber.round([precision]);

Arguments:

1. precision - (number, optional: defaults to 0) The number of digits after the decimal place.

Returns:

§ (number) The number, rounded.

Notes:

§ Argument may also be negative.

Examples:

(12.45).round()   //Returns: 12

(12.45).round(1)  //Returns: 12.5

(12.45).round(-1) //Returns: 10

Number Method: times

Executes the function passed in the specified number of times.

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 seeFunction:bind.

Examples:

(4).times(alert)//Alerts "0", then "1", then "2", then "3".

Number Method: toFloat

Returns this number as a float. Useful because toFloat must work on both Strings and Numbers.

Syntax:

myNumber.toFloat();

Returns:

§ (number) The number as a float.

Examples:

(111).toFloat()//returns 111

(111.1).toFloat()//returns 111.1

Number Method: toInt

Returns this number as another number with the passed in base. Useful because toInt must work on both Strings and Numbers.

Syntax:

myNumber.toInt([base]);

Arguments:

1. base - (number, optional: defaults to 10) The base to use.

Returns:

§ (number) A number with the base provided.

Examples:

(111).toInt()//returns 111

(111.1).toInt()//returns 111

(111).toInt(2)//returns 7

Native: String

A collection of the String Object prototype methods.

See Also:

§ MDC String

String Method: test

Searches for a match between the string and a regular expression. For more information seeMDC Regexp:test.

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:

§ MDC Regular Expressions

String Method: contains

Checks to see if the string passed in is contained in this string. If the separator parameter is passed, will check to see if the string is contained in the list of values separated by that parameter.

Syntax:

myString.contains(string[, separator]);

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

String Method: trim

Trims the leading and trailing spaces off a string.

Syntax:

myString.trim();

Returns:

§ (string) The trimmed string.

Examples:

"    i like cookies     ".trim()//"i like cookies"

String Method: clean

Removes all extraneous whitespace from a string and trims it (String:trim).

Syntax:

myString.clean();

Returns:

§ (string) The cleaned string.

Examples:

" i      like     cookies      \n\n".clean()//returns "i like cookies"

String Method: camelCase

Converts a hyphenated string to a camelcased string.

Syntax:

myString.camelCase();

Returns:

§ (string) The camelcased string.

Examples:

"I-like-cookies".camelCase()//returns "ILikeCookies"

String Method: hyphenate

Converts a camelcased string to a hyphenated string.

Syntax:

myString.hyphenate();

Returns:

§ (string) The hyphenated string.

Examples:

"ILikeCookies".hyphenate()//returns "I-like-cookies"

String Method: capitalize

Converts the first letter of each word in a string to uppercase.

Syntax:

myString.capitalize();

Returns:

§ (string) The capitalized string.

Examples:

"i like cookies".capitalize()//returns "I Like Cookies"

String Method: escapeRegExp

Escapes all regular expression characters from the string.

Syntax:

myString.escapeRegExp();

Returns:

§ (string) The escaped string.

Examples:

'animals.sheep[1]'.escapeRegExp()//returns 'animals\.sheep\[1\]'

String Method: toInt

Parses this string and returns a number of the specified radix or base.

Syntax:

myString.toInt([base]);

Arguments:

1. base - (number, optional) The base to use (defaults to 10).

Returns:

§ (number) The number.

§ (NaN) If the string is not numeric, returns NaN.

Examples:

"4em".toInt()//returns 4

"10px".toInt()//returns 10

See Also:

§ MDC parseInt

String Method: toFloat

Parses this string and returns a floating point number.

Syntax:

myString.toFloat();

Returns:

§ (number) The float.

§ (NaN) 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

String Method: hexToRgb

Converts a hexidecimal color value to RGB. Input string must be in one of the following hexidecimal color formats (with or without the hash). '#ffffff', #fff', 'ffffff', or 'fff'

Syntax:

myString.hexToRgb([array]);

Arguments:

1. array - (boolean, optional) If true is passed, will output an array (eg. [255, 51, 0]) instead of a string (eg. "rgb(255,51,0)").

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]

String Method: rgbToHex

Converts an RGB color value to hexidecimal. Input string must be in one of the following RGB color formats. "rgb(255,255,255)", or "rgba(255,255,255,1)"

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

String Method: stripScripts

Strips the String of its <script> tags and anything in between them.

Syntax:

myString.stripScripts([evaluate]);

Arguments:

1. evaluate - (boolean, optional) If true is passed, the scripts within the String will be evaluated.

Returns:

§ (string) - The String without the stripped scripts.

Examples:

var myString = "<script>alert('Hello')</script>Hello, World.";

myString.stripScripts()//Returns "Hello, World."

myString.stripScripts(true)//Alerts "Hello", then returns "Hello, World."

String Method: substitute

Substitutes keywords in a string using an object/array. Removes undefined keywords and ignores escaped keywords.

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:

§ (string) - The substituted string.

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

String

test

contains

trim

clean

camelCase

hyphenate

capitalize

escapeRegExp

toInt

toFloat

hexToRgb

rgbToHex

stripScripts

substitute

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!

Hash Method: constructor

Syntax:

var myHash = new Hash([object]);

Arguments:

1. object - (mixed) A hash or object to implement.

Returns:

§ (hash) A new Hash instance.

Examples:

var myHash = new Hash({

    aProperty: true,

    aMethod: function(){

        return true;

    }

});

alert(myHash.has('aMethod'))//Returns true.

Hash Method: each

Calls a function for each key-value pair in the object.

Syntax:

myHash.each(fn[, bind]);

Arguments:

1. fn - (function) The function which should be executed on each item in the Hash. This function is passed the item and its key in the Hash.

2. bind - (object, optional) The object to use as 'this' in the function. For more information, seeFunction: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.

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.

Hash Method: has

Tests for the presence of a specified key in the Hash.

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.

Hash Method: keyOf

Returns the key of the specified value. Synonymous with Array:indexOf.

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.

Hash Method: hasValue

Tests for the presence of a specified value in the Hash.

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.

Examples:

var hash = new Hash({'a''one''b''two''c''three'});

hash.hasValue('one')//returns true

hash.hasValue('four')//returns false

Hash Method: extend

Extends this Hash with the key-value pairs from the object passed in.

Syntax:

myHash.extend(properties);

Arguments:

1. properties - (object) The object whose items should be extended into this Hash

Returns:

§ (hash) This Hash, extended.

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' };

Hash Method: combine

Combines this Hash with the key-value pairs of the object passed in. Does not allow duplicates (old values are not overwritten by new ones) and is case and type sensitive.

Syntax:

myHash.combine(properties);

Arguments:

1. properties - (object) The object whose items should be combined into this Hash.

Returns:

§ (hash) This Hash, combined with the new key-value pairs.

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' };

Hash Method: erase

Removes the specified key from the Hash.

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' };

Hash Method: get

Retrieves a value from the hash.

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.

§ (null) null if the key doesn't exist.

Examples:

var hash = new Hash({

    'name''John',

    'lastName''Doe'

});

hash.get('name')//returns 'John'

Hash Method: set

Adds a key-value pair to the hash or replaces a previous value associated with the specified key.

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.

Examples:

var hash = new Hash({

    'name''John',

    'lastName''Doe'

});

hash.set('name''Michelle')//hash.name is now 'Michelle'

Hash Method: empty

Empties the hash.

Syntax:

myHash.empty();

Examples:

var hash = new Hash({

    'name''John',

    'lastName''Doe'

});

hash.empty();

//hash now holds an empty object: {}

Hash Method: include

Includes the specified key-value pair in the Hash if the key doesn't already exist.

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.

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

Hash Method: map

Creates a new map with the results of calling a provided function on every value in the map.

Syntax:

var mappedHash = myHash.map(fn[, bind]);

Arguments:

1. fn - (function) The function to produce an element of the new Hash from an element of the current one.

2. bind - (object, optional) The object to use as 'this' in the function. For more information seeFunction: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:

§ (hash) The new mapped hash.

Examples:

var timesTwo = new Hash({a: 1, b: 2, c: 3}).map(function(value, key){

    return value * 2;

})//timesTwo now holds an object containing: {a: 2, b: 4, c: 6};

Hash Method: filter

Creates a new Hash with all of the elements of the Hash for which the provided filtering function returns true.

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

§ (hash) The new filtered hash.

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}

Hash Method: every

Returns true if every value in the object satisfies the provided testing function.

Syntax:

var allPassed = myHash.every(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:

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

Hash Method: some

Returns true if at least one value in the object satisfies the provided testing function.

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

Hash Method: getClean

Returns a a clean object from an Hash.

Syntax:

myHash.getClean();

Returns:

§ (object) a clean object

Examples:

var hash = new Hash({

    'name''John',

    'lastName''Doe'

});

hash = hash.getClean()// hash doesnt contain Hash prototypes anymore

hash.each() //error!

Hash Method: getKeys

Returns an array containing all the keys, in the same order as the values returned byHash:getValues.

Syntax:

var keys = myHash.getKeys();

Returns:

§ (array) An array containing all the keys of the hash.

Hash Method: getValues

Returns an array containing all the values, in the same order as the keys returned byHash:getKeys.

Syntax:

var values = myHash.getValues();

Returns:

§ (array) An array containing all the values of the hash.

Hash Method: getLength

Returns the number of keys in the Hash.

Syntax:

var length = myHash.getLength();

Returns:

§ (number) The length of the Hash.

Examples:

var hash = new Hash({

    'name''John',

    'lastName''Doe'

});

hash.getLength()// returns 2

Hash Method: toQueryString

Generates a query string from key/value pairs in an object and URI encodes the values.

Syntax:

var queryString = myHash.toQueryString();

Arguments:

1. source - (object) The object to generate the query string from.

Returns:

§ (string) The query string.

Examples:

Using Hash generic:

Hash.toQueryString({apple: "red", lemon: "yellow"})//returns "apple=red&lemon=yellow"

Using Hash instance:

var myHash = new Hash({apple: "red", lemon: "yellow"});

myHash.toQueryString()//returns "apple=red&lemon=yellow"

Utility Functions

Function: $H

Shortcut for the new Hash.

See Also:

§ Hash

Hash

constructor

each

has

keyOf

hasValue

extend

combine

erase

get

set

empty

include

map

filter

every

some

getClean

getKeys

getValues

getLength

toQueryString

Utility

H

Native: Event

MooTools Event Methods.

Event Method: constructor

Syntax:

new Event([event[, win]]);

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.

Event Method: stop

Stop an Event from propagating and also executes preventDefault.

Syntax:

myEvent.stop();

Returns:

§ (object) This Event instance.

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.set('text'"Where do you think you're going?")//'this' is Element that fires the Event.

    (function(){

        this.set('text'"Instead visit the Blog.").set('href''http://blog.mootools.net');

    }).delay(500this);

});

Notes:

§ Returning false within the function can also stop the propagation of the Event.

See Also:

§ Element.addEvent, Element.stopPropagation, Event.preventDefault, Function:delay

Event Method: stopPropagation

Cross browser method to stop the propagation of an event (this stops the event from bubbling up through the DOM).

Syntax:

myEvent.stopPropagation();

Returns:

§ (object) This Event object.

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:

§ Element:addEvent

§ MDC event.stopPropagation

Event Method: preventDefault

Cross browser method to prevent the default action of the event.

Syntax:

myEvent.preventDefault();

Returns:

§ (object) This Event object.

Examples:

HTML:

<form>

    <input id="myCheckbox" type="checkbox" />

</form>

JavaScript

$('myCheckbox').addEvent('click'function(event){

    event.preventDefault()//Will prevent the checkbox from being "checked".

});

See Also:

§ Element:addEvent

§ MDC event.preventDefault

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

});

Native: Class

The base Class of the MooTools framework.

Class Method: constructor

Syntax:

var MyClass = new Class(properties);

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

§ (class) The Class that this class will extend.

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:

§ (class) The created Class.

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

Class Method: implement

Implements the passed in properties into the base Class prototypes, altering the base Class. The same as creating a new Class with the Implements property, but handy when you need to modify existing classes.

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'

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 anyClass, and it is currently implemented in Fx and Request. In Fx, for example, it is used to create custom, complex animations.

Chain Method: constructor

Syntax:

For new classes:

var MyClass = new Class({ Implements: Chain });

For existing classes:

MyClass.implement(Chain);

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

Chain Method: chain

Adds functions to the end of the call stack of the Chain instance.

Syntax:

myClass.chain(fn[, fn2[, fn3[, ...]]]);

Arguments:

1. fn - (function or array) The function (or array of functions) to add to the chain call stack. Will accept and number of functions or arrays 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 out and in twice.

See Also:

§ Fx, Fx.Tween

Chain Method: callChain

Removes the first function of the Chain instance stack and executes it. The next function will then become first in the array.

Syntax:

myClass.callChain([any arguments]);

Arguments:

1. Any arguments passed in will be passed to the "next" function.

Returns:

§ (mixed) The return value of the "next" function or false when the chain was empty.

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

Chain Method: clearChain

Clears the stack of a Chain instance.

Syntax:

myClass.clearChain();

Returns:

§ (object) The current Class instance.

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

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 'complete', 'start', and 'cancel'. 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 });

For existing classes:

MyClass.implement(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 it will be added as an event (e.g. 'onComplete' will add as 'complete' event).

Example:

var Widget = new Class({

    Implements: Events,

    initialize: function(element){

        // ...

    },

    complete: function(){

        this.fireEvent('complete');

    }

});

 

var myWidget = new Widget();

myWidget.addEvent('complete', myFunction);

Notes:

§ Events starting with 'on' are still supported in all methods and are converted to their representation without 'on' (e.g. 'onComplete' becomes 'complete').

See Also:

§ Class, Options

Events Method: addEvent

Adds an event to the Class instance's event stack.

Syntax:

myClass.addEvent(type, fn[, internal]);

Arguments:

1. type - (string) The type of event (e.g. 'complete').

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:

§ (object) This Class instance.

Example:

var myFx = new Fx.Tween('element''opacity');

myFx.addEvent('start', myStartFunction);

Events Method: addEvents

The same as addEvent, but accepts an object to add multiple events at once.

Syntax:

myClass.addEvents(events);

Arguments:

1. events - (object) An object with key/value representing: key the event name (e.g. 'start'), and value the function that is called when the Event occurs.

Returns:

§ (object) This Class instance.

Example:

var myFx = new Fx.Tween('element''opacity');

myFx.addEvents({

    'start': myStartFunction,

    'complete'function() {

        alert('Done.');

    }

});

Events Method: fireEvent

Fires all events of the specified type in the Class instance.

Syntax:

myClass.fireEvent(type[, args[, delay]]);

Arguments:

1. type - (string) The type of event (e.g. 'complete').

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:

§ (object) This Class instance.

Example:

var Widget = new Class({

    Implements: Events,

    initialize: function(arg1, arg2){

        //...

        this.fireEvent("initialize"[arg1, arg2]50);

    }

});

Events Method: removeEvent

Removes an event from the stack of events of the Class instance.

Syntax:

myClass.removeEvent(type, fn);

Arguments:

1. type - (string) The type of event (e.g. 'complete').

2. fn - (function) The function to remove.

Returns:

§ (object) This Class instance.

Notes:

§ If the function has the property internal and is set to true, then the event will not be removed.

Events Method: removeEvents

Removes all events of the given type from the stack of events of a Class instance. If no type is specified, removes all events of all types.

Syntax:

myClass.removeEvents([events]);

Arguments:

1. events - (optional) If not passed removes all events of all types.

§ (string) The event name (e.g. 'success'). Removes all events of that type.

§ (object) An object of type function pairs. Like the one passed to addEvents.

Returns:

§ (object) The current Class instance.

Example:

var myFx = new Fx.Tween('myElement''opacity');

myFx.removeEvents('complete');

Notes:

§ removeEvents will not remove internal events. See Events:removeEvent.

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' adds a 'complete' event).

Syntax:

For new classes:

var MyClass = new Class({Implements: Options});

For existing classes:

MyClass.implement(Options);

Options Method: setOptions

Merges the default options of the Class with the options passed in.

Syntax:

myClass.setOptions([options]);

Arguments:

1. options - (object, optional) The user defined options to merge with the defaults.

Returns:

§ (object) The current Class instance.

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.

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 - The Element to be extended. Can be one of the following types:

§ (element) The element will be extended if it is not already.

§ (string) A string containing the id of the DOM element desired.

§ (object) If the object has a toElement method, toElement will be called to get the Element.

Returns:

§ (element) A DOM element.

§ (null) Null if no matching id was found or if toElement did not return an element.

Examples:

Get a DOM Element by ID:

var myElement = $('myElement');

Get a DOM Element by reference:

var div = document.getElementById('myElement');

div = $(div)//The element with all the Element methods applied.

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 ElementMethods become available.

§ Browsers with native HTMLElement support, such as Safari, Firefox, and Opera, apply all the ElementMethods 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.

Function: $$

Selects and extends DOM elements. Elements arrays returned with $$ will also accept all theElement 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:

§ (array) - An array of all the DOM elements matched, extended with $.

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.

Using CSS Selectors When Selectors is Included:

$$('#myElement')//Returns an array containing only the element with the id 'myElement'.

$$('#myElement a.myClass')//Returns an array of all anchor tags with the class 'myClass' within the DOM element with id 'myElement'.

More Complex $$ Usage:

//Creates an array of all elements and selectors passed as arguments.

$$(myelement1, myelement2, 'a''#myid, #myid2, #myid3', document.getElementsByTagName('div'));

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.

Native: Element

Custom Native to allow all of its methods to be used with any extended DOM Element.

Element Method: constructor

Creates a new Element of the type passed in.

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:

§ (element) A new MooTools extended HTML Element.

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

Element Method: getElement

Gets the first descendant element whose tag name matches the tag provided. If Selectors is included, CSS selectors may also be passed.

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.

Element Method: getElements

Collects all decedent elements whose tag name matches the tag provided. If Selectors is included, CSS selectors may also be passed.

Syntax:

var myElements = myElement.getElements(tag);

Arguments:

1. tag - (string) String of the tag to match.

Returns:

§ (array) An Elements array of all matched Elements.

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.

Element Method: getElementById

Gets the element with the specified id found inside the current Element.

Syntax:

var myElement = anElement.getElementById(id);

Arguments:

1. id - (string) The ID of the Element to find.

Returns:

§ (mixed) If a match is found, returns that Element. Otherwise, returns null.

Examples:

var myChild = $('myParent').getElementById('myChild');

Notes:

§ This method is not provided for Document instances as document.getElementById is provided natively.

Element Method: set

This is a "dynamic arguments" method. Properties passed in can be any of the 'set' properties in the Element.Properties Hash.

Syntax:

myElement.set(arguments);

Arguments:

§ Two Arguments (property, value)

§ property - (string) The string key from the Element.Properties Hash representing the property to set.

§ value - (mixed) The value to set for the specified property.

§ One Argument (properties)

§ properties - (object) Object with its keys/value pairs representing the properties and values to set for the Element (as described below).

Returns:

§ (element) This Element.

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.

§ Whenever using Element:setProperty to set an attribute, pass in the lowercase, simplified form of the property. For example:

§ use 'for', not 'htmlFor',

§ use 'class', not 'className'

§ use 'frameborder', not 'frameBorder'

§ etc.

See Also:

§ Element, Element.Properties, Element:setProperty, Element:addEvents, Element:setStyles

Element Method: get

This is a "dynamic arguments" method. Properties passed in can be any of the 'get' properties in the Element.Properties Hash.

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

Fallback to Element Attributes:

var id = $('myDiv').get('id')//Returns "myDiv".

var value = $('myInput').get('value')//Returns the myInput element's value.

Notes:

§ If the corresponding accessor doesn't exist in the Element.Properties Hash, the result ofElement:getProperty on the property passed in is returned.

See Also:

§ Element, Element.Properties, Element:getProperty

Element Method: erase

This is a "dynamic arguments" method. Properties passed in can be any of the 'erase' properties in the Element.Properties Hash.

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:

§ Element, Element.Properties, Element:removeProperty

Element Method: match

Tests this Element to see if it matches the argument passed in.

Syntax:

myElement.match(match);

Arguments:

1. match - can be a string or element

§ (string) The tag name to test against this element. If Selectors is included, any single CSS selectors may also be passed.

§ (element) An element to match; returns true if this is the actual element passed in.

Returns:

§ (boolean) If the element matched, returns true. Otherwise, returns false.

Examples:

Using a Tag Name:

//Returns true if #myDiv is a div.

$('myDiv').match('div');

Using a CSS Selector:

//Returns true if #myDiv has the class foo and is named "bar"

$('myDiv').match('.foo[name=bar]');

Using an Element:

var el = $('myDiv');

$('myDiv').match(el)//Returns true

$('otherElement').match(el)//Returns false

Element Method: inject

Injects, or inserts, the Element at a particular place relative to the Element's children (specified by the second the argument).

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:

§ (element) This Element.

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>

Inject to the bottom:

JavaScript

myFirstElement.inject(mySecondElement);

Resulting HTML

<div id="mySecondElement">

    <div id="myFirstElement"></div>

</div>

Inject to the top:

JavaScript

myThirdElement.inject(mySecondElement, 'top');

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

Resulting HTML

<div id="mySecondElement"></div>

<div id="myFirstElement"></div>

See Also:

Element:adopt, Element:grab, Element:wraps

Element Method: grab

Works as Element:inject, but in reverse.

Appends the Element at a particular place relative to the Element's children (specified by the where parameter).

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:

§ (element) This Element.

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

Element Method: adopt

Works like Element:grab, but allows multiple elements to be adopted.

Inserts the passed element(s) inside the Element (which will then become the parent element).

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:

§ (element) This Element.

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

Element Method: wraps

Works like Element:grab, but instead of moving the grabbed element from its place, this method moves this Element around its target.

The Element is moved to the position of the passed element and becomes the parent.

Syntax:

myParent.wraps(el[, where]);

Arguments:

1. el - (mixed) The id of an element or an Element.

2. where - (string, optional: default 'bottom') The place to insert the passed in element. Can be 'top' or 'bottom'.

Returns:

§ (element) This Element.

Examples:

HTML

<div id="myFirstElement"></div>

JavaScript

var mySecondElement = new Element('div'{id: 'mySecondElement'});

mySecondElement.wraps($('myFirstElement'));

Resulting HTML

<div id="mySecondElement">

    <div id="myFirstElement"></div>

</div>

Element Method: appendText

Works like Element:grab, but instead of accepting an id or an element, it only accepts text. A text node will be created inside this Element, in either the top or bottom position.

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:

§ (element) The current Element instance.

Examples:

HTML

<div id="myElement">Hey.</div>

JavaScript

$('myElement').appendText(' Howdy.');

Resulting HTML

<div id="myElement">Hey. Howdy.</div>

Element Method: dispose

Removes the Element from the DOM.

Syntax:

var removedElement = myElement.dispose();

Returns:

§ (element) This Element. Useful to always grab the return from this function, as the element could beinjected 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

Element Method: clone

Clones the Element and returns the cloned one.

Syntax:

var copy = myElement.clone([contents, keepid]);

Arguments:

1. contents - (boolean, optional: defaults to true) When set to false the Element's contents are not cloned.

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:

§ (element) The cloned Element.

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 attached events. To clone the events use Element:cloneEvents.

§ Values stored in Element.Storage are not cloned.

§ The clone element and its children are stripped of ids, unless otherwise specified by the keepid parameter.

See Also:

§ Element:cloneEvents.

Element Method: replaces

Replaces the Element with an Element passed.

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:

§ (element) This Element.

Examples:

$('myNewElement').replaces($('myOldElement'));

//$('myOldElement') is gone, and $('myNewElement') is in its place.

See Also:

§ MDC Element:replaceChild

Element Method: hasClass

Tests the Element to see if it has the passed in className.

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>

JavaScript

$('myElement').hasClass('testClass')//returns true

Element Method: addClass

Adds the passed in class to the Element, if the Element doesnt already have it.

Syntax:

myElement.addClass(className);

Arguments:

1. className - (string) The class name to add.

Returns:

§ (element) This Element.

Examples:

HTML

<div id="myElement" class="testClass"></div>

JavaScript

$('myElement').addClass('newClass');

Resulting HTML

<div id="myElement" class="testClass newClass"></div>

Element Method: removeClass

Works like Element:addClass, but removes the class from the Element.

Syntax:

myElement.removeClass(className);

Arguments:

1. className - (string) The class name to remove.

Returns:

§ (element) This Element.

Examples:

HTML

<div id="myElement" class="testClass newClass"></div>

JavaScript

$('myElement').removeClass('newClass');

Resulting HTML

<div id="myElement" class="testClass"></div>

Element Method: toggleClass

Adds or removes the passed in class name to the Element, depending on whether or not it's already present.

Syntax:

myElement.toggleClass(className);

Arguments:

1. className - (string) The class to add or remove.

Returns:

§ (element) This Element.

Examples:

HTML

<div id="myElement" class="myClass"></div>

JavaScript

$('myElement').toggleClass('myClass');

Resulting HTML

<div id="myElement" class=""></div>

JavaScript

$('myElement').toggleClass('myClass');

Resulting HTML

<div id="myElement" class="myClass"></div>

Element Method: getPrevious

Returns the previousSibling of the Element (excluding text nodes).

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:

§ (mixed) The previous sibling Element or null if none found.

Element Method: getAllPrevious

Like Element:getPrevious, but returns a collection of all the matched previousSiblings.

Element Method: getNext

As Element:getPrevious, but tries to find the nextSibling (excluding text nodes).

Syntax:

var nextSibling = myElement.getNext([match]);

Arguments:

1. match - (string, optional): A comma seperated list of tag names to match the found element(s) with. IfSelectors is included, a full CSS selector can be passed.

Returns:

§ (mixed) The next sibling Element or null if none found.

Element Method: getAllNext

Like Element.getNext, but returns a collection of all the matched nextSiblings.

Element Method: getFirst

Works as Element:getPrevious, but tries to find the firstChild (excluding text nodes).

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:

§ (mixed) The first sibling Element or null if none found.

Element Method: getLast

Works as Element:getPrevious, but tries to find the lastChild.

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:

§ (mixed) The first sibling Element, or returns null if none found.

Element Method: getParent

Works as Element:getPrevious, but tries to find the parentNode.

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:

§ (mixed) The target Element's parent or null if no matching parent is found.

Element Method: getParents

Like Element:getParent, but returns a collection of all the matched parentNodes up the tree.

Element Method: getChildren

Returns all the Element's children (excluding text nodes). Returns as Elements.

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.

Element Method: hasChild

Checks all descendants of this Element for a match.

Syntax:

var result = myElement.hasChild(el);

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

Element Method: empty

Empties an Element of all its children.

Syntax:

myElement.empty();

Returns:

§ (element) This Element.

Examples:

HTML

<div id="myElement">

    <p></p>

    <span></span>

</div>

JavaScript

$('myElement').empty();

Resulting HTML

<div id="myElement"></div>

Element Method: destroy

Empties an Element of all its children, removes and garbages the Element. Useful to clear memory before the pageUnload.

Syntax:

myElement.destroy();

Returns:

§ (null)

Element Method: toQueryString

Reads the child inputs of the Element and generates a query string based on their values.

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

Element Method: getSelected

Returns the selected options of a select element.

Syntax:

var selected = mySelect.getSelected();

Returns:

§ (array) An array of the selected elements.

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.

Element Method: getProperty

Returns a single element attribute.

Syntax:

var myProp = myElement.getProperty(property);

Arguments:

§ property - (string) The property to be retrieved.

Returns:

§ (string) A string containing the Element's requested property.

Examples:

HTML

<img id="myImage" src="mootools.png" title="MooTools, the compact JavaScript framework" alt="" />

JavaScript

var imgProps = $('myImage').getProperty('src')//Returns: 'mootools.png'.

Element Method: getProperties

Gets multiple element attributes.

Syntax:

var myProps = myElement.getProperties(properties);

Arguments:

§ properties - (strings) Any number of properties to be retrieved.

Returns:

§ (object) An object containing all of the Element's requested properties.

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: '' }

Element Method: setProperty

Sets an attribute or special property for this Element.

Arguments:

1. property - (string) The property to assign the value passed in.

2. value - (mixed) The value to assign to the property passed in.

Returns:

§ (element) - This Element.

Examples:

HTML

<img id="myImage" />

JavaScript

$('myImage').setProperty('src''mootools.png');

Resulting HTML

<img id="myImage" src="mootools.png" />

Note

§ Whenever using Element:setProperty to set an attribute, pass in the lowercase, simplified form of the property. For example:

§ use 'for', not 'htmlFor',

§ use 'class', not 'className'

§ use 'frameborder', not 'frameBorder'

§ etc.

Element Method: setProperties

Sets numerous attributes for the Element.

Arguments:

1. properties - (object) An object with key/value pairs.

Returns:

§ (element) This Element.

Examples:

HTML

<img id="myImage" />

JavaScript

$('myImage').setProperties({

    src: 'whatever.gif',

    alt: 'whatever dude'

});

Resulting HTML

<img id="myImage" src="whatever.gif" alt="whatever dude" />

Element Method: removeProperty

Removes an attribute from the Element.

Syntax:

myElement.removeProperty(property);

Arguments:

1. property - (string) The attribute to remove.

Returns:

§ (element) This Element.

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>

Element Method: removeProperties

Removes numerous attributes from the Element.

Syntax:

myElement.removeProperties(properties);

Arguments:

1. properties - (strings) The attributes to remove, separated by comma.

Returns:

§ (element) This Element.

Examples:

HTML

<a id="myAnchor" href="#" title="hello world"></a>

JavaScript

$('myAnchor').removeProperties('id''href''title');

Resulting HTML

<a></a>

Element Method: store

Stores an item in the Elements Storage, linked to this Element.

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:

§ (element) This Element.

Example:

$('element').store('someProperty', someValue);

Element Method: retrieve

Retrieves a value from the Elements storage.

Syntax:

myElement.retrieve(key[default]);

Arguments:

1. key - (string) The key you want to retrieve from the storage.

2. default - (mixed, optional) Default value to store and return if no value is stored.

Returns:

§ (mixed) The value linked to the key.

Example:

$('element').retrieve('someProperty')// returns someValue (see example above)

Hash: Element.Properties

This Hash contains the functions that respond to the first argument passed in Element:get,Element:set and Element:erase.

Adding a Custom Element Property

Element.Properties.disabled = {

 

    get: function(){

        return this.disabled;

    }

 

    set: function(value){

        this.disabled = !!value;

        this.setAttribute('disabled', !!value);

    }

 

};

Using a Custom Element Property

//Gets the "disabled" property.

$(element).get('disabled');

//Sets the "disabled" property to true, along with the attribute.

$(element).set('disabled'true);

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});

Element Property: html

Setter:

Sets the innerHTML of the Element.

Syntax:

myElement.set('html'[htmlString[, htmlString2[, htmlString3[, ..]]]);

Arguments:

1. Any number of string parameters with HTML.

Returns:

§ (element) This Element.

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:

§ (text) This Element's innerHTML.

Element Property: text

Setter:

Sets the inner text of the Element.

Syntax:

myElement.set('text', text);

Arguments:

1. text - (string) The new text content for the Element.

Returns:

§ (element) This Element.

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:

§ (string) The text of the Element.

Examples:

HTML

<div id="myElement">my text</div>

JavaScript

var myText = $('myElement').get('text')//myText = 'my text'.

Element Property: tag

Getter:

Returns the tag name of the Element in lower case.

Syntax:

var myTag = myElement.get('tag');

Returns:

§ (string) The tag name in lower case.

Examples:

HTML

<img id="myImage" />

JavaScript

var myTag = $('myImage').get('tag')// myTag = 'img'.

Native: IFrame

Custom Native to create and easily work with IFrames.

IFrame Method: constructor

Creates an IFrame HTML Element and extends its window and document with MooTools.

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 asElement:constructor props argument.

Returns:

§ (element) A new IFrame HTML Element.

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

        }

 

    }

 

});

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.

Native: Elements

The Elements class allows Element methods to work on an Elements array, as well as ArrayMethods.

Elements Method: constructor

Syntax:

var myElements = new Elements(elements[, options]);

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

Create Elements From an Array:

var myElements = new Elements(['myElementID', $('myElement')'myElementID2', document.getElementById('myElementID3')]);

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 Elementand Elements methods.

§ Every node of the Elements instance has all the Element methods.

See Also:

§ $$, $, Element, Elements, Array

Elements Method: filter

Filters a collection of elements by a given tag name. If Selectors is included, this method will be able to filter by any selector. It also works like Array:filter, by filtering collection of elements with a function.

Syntax:

var filteredElements = elements.filter(selector);

Arguments:

1. selector - (mixed) A single CSS selector.

Returns:

§ (array) A subset of this Elements instance.

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.

Element Method: addEvent

Attaches an event listener to a DOM element.

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:

§ (element) This Element.

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:

§ w3schools Event Attributes

Element Method: removeEvent

Works as Element.addEvent, but instead removes the specified event listener.

Syntax:

myElement.removeEvent(type, fn);

Arguments:

1. type - (string) The event name.

2. fn - (function) The function to remove.

Returns:

§ (element) This Element.

Examples:

Standard usage:

var destroy = function(){ alert('Boom: ' + this.id)} // this refers to the Element.

$('myElement').addEvent('click', destroy);

 

// later

$('myElement').removeEvent('click', destroy);

Examples with bind:

var destroy = function(){ alert('Boom: ' + this.id)}

var boundDestroy = destroy.bind($('anotherElement'));

$('myElement').addEvent('click', boundDestroy);

 

// later

$('myElement').removeEvent('click', destroy)// this won't remove the event.

$('myElement').removeEvent('click', destroy.bind($('anotherElement'))// this won't remove the event either.

$('myElement').removeEvent('click', boundDestroy)// this is the correct way to remove the event.

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.

Element Method: addEvents

The same as Element:addEvent, but accepts an object to add multiple events at once.

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:

§ (element) This Element.

Examples:

$('myElement').addEvents({

    'mouseover'function(){

        alert('mouseover');

    },

    'click'function(){

        alert('click');

    }

});

Notes:

§ This method is also attached to Document and Window.

See Also:

§ Element:addEvent

Element Method: removeEvents

Removes all events of a certain type from an Element. If no argument is passed, removes all events of all types.

Syntax:

myElements.removeEvents([events]);

Arguments:

1. events - (optional) if not passed removes all events from the element.

§ (string) The event name (e.g. 'click'). Removes all events of that type.

§ (object) An object of type function pairs. Like the one passed to Element:addEvent.

Returns:

§ (element) This Element.

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:

§ This method is also attached to Document and Window.

See Also:

§ Element:removeEvent

Element Method: fireEvent

Executes all events of the specified type present in the Element.

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:

§ (element) This Element.

Examples:

// Fires all the added 'click' events and passes the Element 'anElement' after one second.

$('myElement').fireEvent('click', $('anElement')1000);

Notes:

§ This will not fire the DOM Event (this concerns all inline events ie. onmousedown="..").

§ This method is also attached to Document and Window.

Element Method: cloneEvents

Clones all events from an Element to this Element.

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:

§ (element) This Element.

Examples:

var myElement = $('myElement');

var myClone = myElement.clone().cloneEvents(myElement)//clones the element and its events

Notes:

§ This method is also attached to Document and Window.

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.

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:

§ Custom Events with only base: they will just be a redirect to the base event.

§ Custom Events with base and condition: they will be redirect to the base event, but only fired if the condition is met.

§ 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);

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

Native: Element

Custom Native to allow all of its methods to be used with any DOM element via the dollar function $.

Element Method: setStyle

Sets a CSS property to the Element.

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:

§ (element) This element.

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.

Element Method: getStyle

Returns the style of the Element given the property passed in.

Syntax:

var style = myElement.getStyle(property);

Arguments:

1. property - (string) The css style property you want to retrieve.

Returns:

§ (string) The style value.

Examples:

$('myElement').getStyle('width')//Returns "300px".

$('myElement').getStyle('width').toInt()//Returns 300.

Element Method: setStyles

Applies a collection of styles to the Element.

Syntax:

myElement.setStyles(styles);

Arguments:

1. styles - (object) An object of property/value pairs for all the styles to apply.

Returns:

§ (element) This element.

Example:

$('myElement').setStyles({

    border: '1px solid #000',

    width: 300,

    height: 400

});

See Also:

§ Element:getStyle

Element Method: getStyles

Returns an object of styles of the Element for each argument passed in.

Syntax:

var styles = myElement.getStyles(property[, property2[, property3[, ...]]]);

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

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.

Element Method: scrollTo

Scrolls the element to the specified coordinated (if the element has an overflow). The following method is also available on the Window object.

Syntax:

myElement.scrollTo(x, y);

Arguments:

1. x - (number) The x coordinate.

2. y - (number) The y coordinate.

Example:

$('myElement').scrollTo(0100);

See Also:

§ MDC Element:scrollLeft, MDC Element:scrollTop

Element Method: getSize

Returns the height and width of the Element, taking into account borders and padding. The following method is also available on the Window object.

Syntax:

myElement.getSize();

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

Element Method: getScrollSize

Returns an Object representing the size of the target Element, including scrollable area. The following method is also available on the Window object.

Syntax:

myElement.getScrollSize();

Returns:

§ (object) An object containing the x and y dimensions of the target Element.

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

Element Method: getScroll

Returns an Object representing how far the target Element is scrolled in either direction. The following method is also available on the Window object.

Syntax:

myElement.getScroll();

Returns:

§ (object) An object containing the x and y dimensions of the target Element's scroll.

Example:

var scroll = $('myElement').getScroll();

alert('My element is scrolled down ' + scroll.y + 'px')//alerts 'My element is scrolled down to 620px'

Element Method: getPosition

Returns the real offsets of the element.

Syntax:

myElement.getPosition(relative);

Arguments:

relative - (Element, defaults to the document) If set, the position will be relative to this Element.

Returns:

§ (object) An object with the x and y coordinates of the Element's position.

Example:

$('element').getPosition()//returns {x: 100, y: 500};

See Also:

§ QuirksMode: Find position

Element Method: getCoordinates

Returns an object with width, height, left, right, top, and bottom coordinate values of the Element.

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.

Example:

var myValues = $('myElement').getCoordinates();

Returns:

{

    top: 50,

    left: 100,

    width: 200,

    height: 300,

    right: 300,

    bottom: 350

}

See Also:

Element:getPosition

Native: Element

Custom class to allow all of its methods to be used with any Selectors element via the dollar function $.

Element Property: getElements

Gets all the elements within an element that match the given selector.

Syntax:

var myElements = myElement.getElements(selector);

Arguments:

1. selector - (string) The CSS Selector to match.

Returns:

§ (array) An Element collection.

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:

§ Supports these operators in attribute selectors:

§ '=' : is equal to

§ '^=' : starts-with

§ '$=' : ends-with

§ '!=' : is not equal to

Element Property: getElement

Same as Element:getElements, but returns only the first.

Syntax:

var anElement = myElement.getElement(selector);

Arguments:

1. selector - (string) The CSS Selector to match.

Returns:

§ (mixed) An extended Element, or null if not found.

Example:

var found = $('myElement').getElement('.findMe').setStyle('color''#f00');

Selectors.Pseudo

Some default Pseudo Selectors for Selectors.

See Also:

§ W3C Pseudo Classes

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

Variables:

2. text - (string) The text that the Element should contain.

Example:

$$('p:contains("find me")');

Selector: nth-child

Matches every nth child.

Usage:

Nth Expression:

':nth-child(nExpression)'

Variables:

§ nExpression - (string) A nth expression for the "every" nth-child.

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.

Every Odd Child:

':nth-child(odd)'

Every Even Child:

':nth-child(even)'

Only Child:

':nth-child(only)'

First Child:

'nth-child(first)'

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.

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

Window Event: domready

Contains the window Event 'domready', which will execute when the DOM has loaded. To ensure that DOM elements exist when the code attempting to access them is executed, they should be placed within the 'domready' event.

This event is only available to the window Element.

Example:

window.addEvent('domready'function() {

    alert("The DOM is ready.");

});

See Also:

Element.Event

Object: JSON

JSON parser and encoder.

See Also:

§ JavaScript Object Notation (JSON.org)

JSON Method: encode

Converts an object or array to a JSON string.

Syntax:

var myJSON = JSON.encode(obj);

Arguments:

1. obj - (object) The object to convert to string.

Returns:

§ (string) A JSON string.

Examples:

var fruitsJSON = JSON.encode({apple: 'red', lemon: 'yellow'})// returns: '{"apple":"red","lemon":"yellow"}'

JSON Method: decode

Converts a JSON string into an JavaScript object.

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:

§ (object) The object represented by the JSON string.

Examples:

var myObject = JSON.decode('{"apple":"red","lemon":"yellow"}')//returns: {apple: 'red', lemon: 'yellow'}

Credits:

§ JSON test regexp is by Douglas Crockford and Tobie Langel.

Object: Cookie

Sets and accesses cookies.

Credits:

§ Based on the functions by Peter-Paul Koch QuirksMode.

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.

Cookie Method: write

Writes a cookie in the browser.

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

Saves the Cookie for a Day:

var myCookie  = Cookie.write('username''JackBauer'{duration: 1});

Cookie Method: read

Reads the value of a Cookie.

Syntax:

var myCookie = Cookie.read(name);

Arguments:

2. name - (string) The name of the Cookie to retrieve.

Returns:

§ (mixed) The cookie string value, or null if not found.

Examples:

Cookie.read("username");

Cookie Method: dispose

Removes a cookie from the browser.

Syntax:

var oldCookie = Cookie.dispose(cookie[, options]);

Arguments:

3. name - (string) The name of the cookie to remove or a previously saved Cookie instance.

4. options - (object, optional) See Cookie.

Examples:

Remove a Cookie:

Cookie.dispose('username')//Bye-bye JackBauer! Seeya in 24 Hours.

Creating a Cookie and Removing it Right Away:

var myCookie = Cookie.write('username''Aaron'{domain: 'mootools.net'});

if (Cookie.read('username') == 'Aaron') { Cookie.dispose(myCookie)}

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.

§ callBacks - (object) Functions to call from the SWF. These will be available globally in the movie, and bound to the object.

Returns:

§ (element) A new HTML object Element.

Example:

var obj = new Swiff('myMovie.swf'{

    id: 'myBeautifulMovie',

    width: 500,

    height: 400,

    params: {

        wmode: 'opaque',

        bgcolor: '#ff3300'

    },

    vars: {

        myVariable: myJsVar,

        myVariableString: 'hello'

    },

    callBacks: {

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

Swiff Function: remote

Calls an ActionScript function from JavaScript.

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:

§ (mixed) The ActionScript function's result.

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.

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:

2. ChainEventsOptions

Fx Method: constructor

Syntax:

var myFx = new Fx([options]);

Arguments:

§ options - (object, optional) An object with options for the effect. See below.

Options:

2. fps - (number: defaults to 50) The frames per second for the transition.

3. unit - (string: defaults to false) The unit, e.g. 'px', 'em', or '%'. See Element:setStyle.

4. link - (string: defaults to ignore) Can be 'ignore', 'cancel' and 'chain'.

· '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 'sine:in:out' The equation to use for the effect seeFx.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:

3. start - (function) The function to execute when the effect begins.

4. cancel - (function) The function to execute when you manually stop the effect.

5. complete - (function) The function to execute after the effect has processed.

6. chainComplete - (function) The function to execute when using link 'chain' (see options). It gets called after all effects in the chain have completed.

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:

5. Fx.TweenFx.Morph.

Fx Method: start

The start method is used to begin a transition. Fires the 'start' event.

Syntax:

myFx.start(from[, to]);

Arguments:

§ from - (mixed) The starting value for the effect. If only one argument is provided, this value will be used as the target value.

§ to - (mixed, optional) The target value for the effect.

Returns:

2. (object) - This Fx instance.

Examples:

§ See examples in the documentation for each Fx subclass.

Notes:

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

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

Arguments:

§ value - (mixed) The value to immediately apply to the transition.

Returns:

2. (object) - This Fx instance.

Examples:

§ See examples in the documentation for each Fx subclass.

Fx Method: cancel

The cancel method is used to cancel a running transition. Fires the 'cancel' event.

Syntax:

myFx.cancel();

Returns:

4. (object) - This Fx instance.

Fx Method: pause

Temporarily pause a currently running effect.

Syntax:

myFx.pause();

Returns:

4. (object) - This Fx instance.

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.

Syntax:

myFx.resume();

Returns:

§ (object) - This Fx instance.

Notes:

3. The effect will only be resumed if it has been previously paused. Otherwise, the call to resume will be ignored.

Class: Fx.CSS

CSS parsing class for effects. Required by Fx.Tween, Fx.Morph, Fx.Elements.

Has no public methods.

Class: Fx.Tween

Contains Fx.Tween and the Element shortcut Element.tween.

Extends:

Fx

Fx.Tween Method: constructor

The Tween effect, used to transition any CSS property from one value to another.

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

Fx.Tween Method: set

Sets the Element's CSS property to the specified value immediately.

Syntax:

myFx.set(property, value);

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:

§ (object) This Fx.Tween instance.

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.

Fx.Tween Method: start

Transitions the Element's CSS property to the specified value.

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, optional) The starting CSS property value for the effect.

3. to - (mixed) The target CSS property value for the effect.

Returns:

§ (object) This Fx.Tween instance.

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

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.

Hash: Element.Properties

see Element.Properties

Element Property: tween

Sets and gets default options for the Fx.Tween instance of an Element.

Setter:

Syntax:

el.set('tween'[, options]);

Arguments:

§ options - (object) the Fx.Tween options.

Returns:

§ (element) This Element.

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:

§ (object) The Element's internal Fx.Tween instance.

Examples:

el.get('tween'{property: 'opacity', duration: 'long'}).start(0);

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

Native: Element

Custom Native to allow all of its methods to be used with any DOM element via the dollar function $.

Element Method: tween

Element shortcut method which immediately transitions any single CSS property of an Element from one value to another.

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:

§ (element) This Element.

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'[20200]);

//Transitions the border of "myElement" from its current to "6px solid blue":

$('myElement').tween('border''6px solid #36f');

See Also:

§ Fx.Tween

Element Method: fade

Element shortcut method for tween with opacity. Useful for fading an Element in and out or to a certain opacity level.

Syntax:

myElement.fade([how]);

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.

Element Method: highlight

Element shortcut method for tweening the background color. Immediately transitions an Element's background color to a specified highlight color then back to its set background color.

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:

§ (element) This Element.

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

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:

§ (object) A new Fx.Morph instance.

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'[10100]//Morphs the 'height' style from 10px to 100px.

    'width'[900300]  //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');

See Also:

§ Fx

Fx.Morph Method: set

Sets the Element's CSS properties to the specified values immediately.

Syntax:

myFx.set(to);

Arguments:

1. properties - (mixed) Either an object of key/value pairs of CSS attributes to change or a stringrepresenting 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:

§ (object) This Fx.Morph instance.

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

Fx.Morph Method: start

Executes a transition for any number of CSS properties in tandem.

Syntax:

myFx.start(properties);

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:

§ (object) This Fx.Morph instance.

Examples:

var myEffects = new Fx.Morph('myElement'{duration: 1000, transition: Fx.Transitions.Sine.easeOut});

 

myEffects.start({

    'height'[10100],

    'width'[900300],

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

Hash: Element.Properties

see Element.Properties

Element Property: morph

Setter

Sets a default Fx.Morph instance for an Element.

Syntax:

el.set('morph'[, options]);

Arguments:

1. options - (object, optional) The Fx.Morph options.

Returns:

§ (element) This Element.

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:

§ (object) The Fx.Morph instance.

Examples:

el.set('morph'{duration: 'long', transition: 'bounce:out'});

el.morph({height: 100, width: 100});

el.get('morph')//The Fx.Morph instance.

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:

§ (element) This Element.

Example:

With an object:

$('myElement').morph({height: 100, width: 200});

With a selector:

$('myElement').morph('.class1');

See Also:

§ Fx.Morph

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

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:

§ Robert Penner's Easing Equations

Fx.Transitions Method: linear

Displays a linear transition.

Fx.Transitions Method: quad

Displays a quadratic transition. Must be used as Quad.easeIn or Quad.easeOut or Quad.easeInOut.

Fx.Transitions Method: cubic

Displays a cubicular transition. Must be used as Cubic.easeIn or Cubic.easeOut or Cubic.easeInOut.

Fx.Transitions Method: quart

Displays a quartetic transition. Must be used as Quart.easeIn or Quart.easeOut or Quart.easeInOut.

Fx.Transitions Method: quint

Displays a quintic transition. Must be used as Quint.easeIn or Quint.easeOut or Quint.easeInOut

Fx.Transitions Method: pow

Used to generate Quad, Cubic, Quart and Quint.

Note:

§ The default is p^6.

Fx.Transitions Method: expo

Displays a exponential transition. Must be used as Expo.easeIn or Expo.easeOut or Expo.easeInOut.

Fx.Transitions Method: circ

Displays a circular transition. Must be used as Circ.easeIn or Circ.easeOut or Circ.easeInOut.

Fx.Transitions Method: sine

Displays a sineousidal transition. Must be used as Sine.easeIn or Sine.easeOut or Sine.easeInOut.

Fx.Transitions Method: back

Makes the transition go back, then all forth. Must be used as Back.easeIn or Back.easeOut or Back.easeInOut.

Fx.Transitions Method: bounce

Makes the transition bouncy. Must be used as Bounce.easeIn or Bounce.easeOut or Bounce.easeInOut.

Fx.Transitions Method: elastic

Elastic curve. Must be used as Elastic.easeIn or Elastic.easeOut or Elastic.easeInOut

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 Fx.Transitions 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:

§ (function) A function with easing functions.

Examples:

//Elastic.easeOut with user-defined value for elasticity.

var myTransition = new Fx.Transition(Fx.Transitions.Elastic3);

var myFx = $('myElement').effect('margin'{transition: myTransition.easeOut});

See Also:

§ Fx.Transitions

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.

link - (string: defaults to 'ignore') Can be 'ignore', 'cancel' and 'chain'.

'ignore' - Any calls made to start while the request is running will be ignored. (Synonymous with 'wait': true from 1.11)

'cancel' - Any calls made to start while the request is running will take precedence over the currently running request. The new request will start immediately, canceling the one that is currently running. (Synonymous with 'wait': false from 1.11)

'chain' - Any calls made to start while the request is running will be chained up, and will take place as soon as the current request has finished, one after another.

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.

headers - (object) An object to use in order to set the request headers.

isSuccess - (function) Overrides the built-in isSuccess function.

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. Responses with javascript content-type will be evaluated automatically.

emulation - (boolean: defaults to true) If set to true, other methods than 'post' or 'get' are appended as post-data named '_method' (used in rails)

urlEncoded - (boolean: defaults to true) If set to true, the content-type header is set to www-form-urlencoded + encoding

Events:

request

Fired when the Request is sent.

Signature:

onRequest()

complete

Fired when the Request is completed.

Signature:

onComplete()

cancel

Fired when a request has been cancelled.

Signature:

onCancel()

success

Fired when the Request is completed successfully.

Signature:

onSuccess(responseText, responseXML)

Arguments:

responseText - (string) The returned text from the request.

responseXML - (mixed) The response XML from the request.

failure

Fired when the request failed (error status code).

Signature:

onFailure(xhr)

Arguments:

xhr - (XMLHttpRequest) The transport instance.

exception

Fired when setting a request header fails.

Signature:

onException(headerName, value)

Arguments:

headerName - (string) The name of the failing header.

value - (string) The value of the failing header.

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 'success' event.

Returns:

(object) A new Request instance.

Example:

var myRequest = new Request({method: 'get', url: 'requestHandler.php'});

myRequest.send('name=john&lastname=dorian');

See Also:

Wikipedia: XMLHttpRequest

Request Method: setHeader

Add or modify a header for the request. It will not override headers from the options.

Syntax:

myRequest.setHeader(name, value);

Arguments:

name - (string) The name for the header.

value - (string) The value to be assigned.

Returns:

(object) This Request instance.

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

Request Method: getHeader

Returns the given response header or null if not found.

Syntax:

myRequest.getHeader(name);

Arguments:

name - (string) The name of the header to retrieve the value of.

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

Request Method: send

Opens the Request connection and sends the provided data with the specified options.

Syntax:

myRequest.send([options]);

Arguments:

options - (object, optional) The options for the sent Request. Will also accept data as a query string for compatibility reasons.

Returns:

(object) This Request instance.

Examples:

var myRequest = new Request({url: 'http://localhost/some_url'}).send("save=username&name=John");

Request Method: cancel

Cancels the currently running request, if any.

Syntax:

myRequest.cancel();

Returns:

(object) This Request instance.

Example:

var myRequest = new Request({url: 'mypage.html', method: 'get'}).send('some=data');

myRequest.cancel();

Hash: Element.Properties

see Element.Properties

Element Property: send

Setter

Sets a default Request instance for an Element. This is useful when handling forms.

Syntax:

el.set('send'[, options]);

Arguments:

options - (object) The Request options.

Returns:

(element) The original element.

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:

options - (object, optional) The Request options. If passed, this method will generate a new instance of the Request class.

Returns:

(object) The Request instance.

Example:

el.get('send', {method: 'get'});

el.send();

el.get('send'); //Returns the Request instance.

Native: Element

Custom Native to allow all of its methods to be used with any DOM element via the dollar function $.

Element Method: send

Sends a form or a container of inputs with an HTML request.

Syntax:

myElement.send(url);

Arguments:

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:

(element) This Element.

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:

The URL is taken from the action attribute of the form.

Class: Request.HTML

Request Specifically made for receiving HTML.

Extends:

Request

Syntax:

var myHTMLRequest = new Request.HTML([options]);

Arguments:

options - (object, optional) See options below. Also inherited are all the options from Request.

Options:

update - (element: defaults to null) The Element to insert the response text of the Request into upon completion of the request.

Events:

success

(function) Function to execute when the HTML request completes. This overrides the signature of the Request success event.

Signature:

onSuccess(responseTree, responseElements, responseHTML, responseJavaScript)

Arguments:

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:

(object) A new Request.HTML instance.

Examples:

Simple GET Request:

var myHTMLRequest = new Request.HTML().get('myPage.html');

POST Request with data as String:

var myHTMLRequest = new Request.HTML({url:'myPage.html'}).post("user_id=25&save=true");

Data from Object Passed via GET:

//Loads "load/?user_id=25".

var myHTMLRequest = new Request.HTML({url:'load/'}).get({'user_id': 25});

Data from Element via POST:

HTML

<form action="save/" method="post" id="user-form">

    <p>

        Search: <input type="text" name="search" />

        Search in description: <input type="checkbox" name="search_description" value="yes" />

        <input type="submit" />

    </p>

</form>

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

Hash: Element.Properties

see Element.Properties

Element Property: load

Setter

Sets a default Request.HTML instance for an Element.

Syntax:

el.set('load'[, options]);

Arguments:

options - (object) The Request options.

Returns:

(element) The target Element.

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:

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:

(object) The Request instance.

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

Native: Element

Custom Native to allow all of its methods to be used with any DOM element via the dollar function $.

Element Method: load

Updates the content of the Element with a Request.HTML GET request.

Syntax:

myElement.load(url);

Arguments:

url - (string) The URL pointing to the server-side document.

Returns:

(element) The target Element.

Example:

HTML

<div id="content">Loading content...</div>

JavaScript

$('content').load('page_1.html');

See Also:

$, Request

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:

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

Events:

success

Fired when the request completes. This overrides the signature of the Request success event.

Signature:

onSuccess(responseJSON, responseText)

Arguments:

responseJSON - (object) The JSON response object from the remote request.

responseText - (string) The JSON response as string.

Returns:

(object) A new Request.JSON instance.

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

Request.JSON

Class: Fx.Slide

The slide effect slides an Element in horizontally or vertically. The contents will fold inside.

Note:

§ Fx.Slide requires the page to be in Standards Mode.

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.

Fx.Slide Method: slideIn

Slides the Element in view horizontally or vertically.

Syntax:

myFx.slideIn([mode]);

Arguments:

1. mode - (string, optional) Override the passed in Fx.Slide option with 'horizontal' or 'vertical'.

Returns:

§ (object) This Fx.Slide instance.

Examples:

var myFx = new Fx.Slide('myElement').slideOut().chain(function(){

    this.show().slideIn('horizontal');

});

Fx.Slide Method: slideOut

Slides the Element out of view horizontally or vertically.

Syntax:

myFx.slideOut([mode]);

Arguments:

1. mode - (string, optional) Override the passed in Fx.Slide option with 'horizontal' or 'vertical'.

Returns:

§ (object) This Fx.Slide instance.

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

Fx.Slide Method: toggle

Slides the Element in or out, depending on its state.

Syntax:

myFx.toggle([mode]);

Arguments:

1. mode - (string, optional) Override the passed in Fx.Slide option with 'horizontal' or 'vertical'.

Returns:

§ (object) This Fx.Slide instance.

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

Fx.Slide Method: hide

Hides the Element without a transition.

Syntax:

myFx.hide([mode]);

Arguments:

1. mode - (string, optional) Override the passed in Fx.Slide option with 'horizontal' or 'vertical'.

Returns:

§ (object) This Fx.Slide instance.

Examples:

var myFx = new Fx.Slide('myElement'{

    duration: 'long',

    transition: Fx.Transitions.Bounce.easeOut

});

 

//Automatically hides and then slies in "myElement":

myFx.hide().slideIn();

Fx.Slide Method: show

Shows the Element without a transition.

Syntax:

myFx.show([mode]);

Arguments:

1. mode - (string, optional) Override the passed in Fx.Slide option with 'horizontal' or 'vertical'.

Returns:

§ (object) This Fx.Slide instance.

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(1000this);

});

Hash: Element.Properties

See Element.Properties.

Element Property: slide

Sets a default Fx.Slide instance for an element. Gets the previously setted Fx.Slide instance or a new one with default options.

Syntax:

el.set('slide'[, options]);

Arguments:

1. options - (object) the Fx.Morph options.

Returns:

§ (element) this element

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:

§ (object) the Fx.Slide instance

Examples:

el.set('slide'{duration: 'long', transition: 'bounce:out'});

el.slide('in');

 

el.get('slide')//the Fx.Slide instance

Native: Element

Custom Native to allow all of its methods to be used with any DOM element via the dollar function $.

Element Method: slide

Slides this Element in view.

Syntax:

myElement.slide(how);

Arguments:

1. how - (string, optional) Can be 'in', 'out', 'toggle', 'show' and 'hide'. Defaults to 'toggle'.

Returns:

§ (element) this Element.

Examples:

$('myElement').slide('hide').slide('in');

Class: Fx.Scroll

Scrolls any element with an overflow, including the window element.

Note:

§ Fx.Scroll requires the page to be in Standards Mode.

Extends:

§ Fx

Fx.Scroll Method: constructor

Syntax:

var myFx = new Fx.Scroll(element[, options]);

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:

§ (object) A new Fx.Scroll instance.

Examples:

var myFx = new Fx.Scroll('myElement'{

    offset: {

        'x'0,

        'y'100

    }

}).toTop();

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.

Fx.Scroll Method: set

Scrolls the specified Element to the x/y coordinates immediately.

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:

§ (object) This Fx.Scroll instance.

Examples:

var myElement = $(document.body);

var myFx = new Fx.Scroll(myElement).set(00.5 * document.body.offsetHeight);

Fx.Scroll Method: start

Scrolls the specified Element to the x/y coordinates provided.

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:

§ (object) This Fx.Scroll instance.

Examples:

var myElement = $(document.body);

var myFx = new Fx.Scroll(myElement).start(00.5 * document.body.offsetHeight);

Notes:

§ Scrolling to negative coordinates is impossible.

Fx.Scroll Method: toTop

Scrolls the specified Element to its maximum top.

Syntax:

myFx.toTop();

Returns:

§ (object) This Fx.Scroll instance.

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(1500this);

    }

}).scrollTo(0200).chain(function(){

    this.scrollTo(2000);

});

Fx.Scroll Method: toBottom

Scrolls the specified Element to its maximum bottom.

Syntax:

myFx.toBottom();

Returns:

§ (object) This Fx.Scroll instance.

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(1000this);

});

Fx.Scroll Method: toLeft

Scrolls the specified Element to its maximum left.

Syntax:

myFx.toLeft();

Returns:

§ (object) This Fx.Scroll instance.

Examples:

//Scrolls "myElement" 200 pixels to the right and then back.

var myFx = new Fx.Scroll('myElement').scrollTo(2000).chain(function(){

    this.toLeft();

});

Fx.Scroll Method: toRight

Scrolls the specified Element to its maximum right.

Syntax:

myFx.toRight();

Returns:

§ (object) This Fx.Scroll instance.

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

Fx.Scroll Method: toElement

Scrolls the specified Element to the position the passed in Element is found.

Syntax:

myFx.toElement(el);

Arguments:

1. el - (mixed) A string of the Element's id or an Element reference to scroll to.

Returns:

§ (object) This Fx.Scroll instance.

Examples:

//Scrolls the "myElement" to the top left corner of the window.

var myFx = new Fx.Scroll(window).toElement('myElement');

Notes:

§ See Element:getPosition for position difficulties.

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:

§ (object) A new Fx.Elements instance.

Examples:

var myFx = new Fx.Elements($$('.myElementClass'){

    onComplete: function(){

        alert('complete');

    }

}).start({

    '0'{

        'height'[200300],

        'opacity'[0,1]

    },

    '1'{

        'width'[200300],

        'opacity'[1,0]

    }

});

Notes:

§ Includes colors but must be in hex format.

Fx.Elements Method: set

Applies the passed in style transitions to each object named immediately (see example).

Syntax:

myFx.set(to);

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:

§ (object) This Fx.Elements instance.

Examples:

var myFx = new Fx.Elements($$('.myClass')).set({

    '0'{

        'height'200,

        'opacity'0

    },

    '1'{

        'width'300,

        'opacity'1

    }

});

Fx.Elements Method: start

Applies the passed in style transitions to each object named (see example).

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:

§ (object) This Fx.Elements instance.

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

    }

});

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

Drag Method: constructor

Syntax:

var myDragInstance = new Drag(el[, options]);

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:

§ beforeStart - Executed before the Drag instance attaches the events. Receives the dragged element as an argument.

§ start - Executed when the user starts to drag (on mousedown). Receives the dragged element as an argument.

§ snap - Executed when the user has dragged past the snap option. Receives the dragged element as an argument.

§ drag - Executed on every step of the drag. Receives the dragged element as an argument.

§ complete - Executed when the user completes the drag. Receives the dragged element as an argument.

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:

§ Drag requires the page to be in Standards Mode.

See Also:

§ W3Schools: CSS Units

Drag Method: attach

Attaches the mouse listener to the handle, causing the Element to be draggable.

Syntax:

myDrag.attach();

Returns:

§ (object) This Drag instance.

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:

§ $, Element:makeDraggable, Drag:detach, Element:addEvent

Drag Method: detach

Detaches the mouse listener from the handle, preventing the Element from being dragged.

Syntax:

myDrag.detach();

Returns:

§ (object) This Drag instance.

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

Drag Method: stop

Stops (removes) all attached events from the Drag instance and executes the 'complete' Event.

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

        }

    }

});

Native: Element

Custom Native to allow all of its methods to be used with any DOM element via the dollar function $.

Element Method: makeResizable

Adds drag-to-resize behavior to an Element using supplied options.

Syntax:

var myResize = myElement.makeResizable([options]);

Arguments:

1. options - (object, optional) See [Drag][] for acceptable options.

Returns:

§ (object) The Drag instance that was created.

Examples:

var myResize = $('myElement').makeResizable({

    onComplete: function(){

        alert('Done resizing.');

    }

});

See Also:

§ Drag

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

Note:

Drag.Move requires the page to be in Standards Mode.

Drag.Move Method: constructor

Syntax:

var myMove = new Drag.Move(myElement[, options]);

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. The class's drop, enter, and leave events will be fired in conjunction with interaction with one of these elements.

Events:

§ drop - Executed when the element drops. Passes as argument the element and the element dropped on. If dropped on nothing, the second argument is null.

§ leave - Executed when the element leaves one of the droppables.

§ enter - Executed when the element enters one of the droppables.

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:

§ Drag.Cart - http://demos.mootools.net/Drag.Cart

§ Drag.Absolutely - http://demos.mootools.net/Drag.Absolutely

§ DragDrop - http://demos.mootools.net/DragDrop

See Also:

§ Drag

Drag.Move Method: stop

Checks if the Element is above a droppable and fires the drop event. Else, fires the 'emptydrop' event that is attached to this Element. Lastly, calls the Drag Class stop method.

Syntax:

myMove.stop();

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

Native: Element

Custom Native to allow all of its methods to be used with any DOM element via the dollar function $.

Element Method: makeDraggable

Adds drag-to-move behavior to an Element using supplied options.

Syntax:

var myDrag = myElement.makeDraggable([options]);

Arguments:

1. options - (object, optional) See Drag and Drag.Move for acceptable options.

Returns:

§ (object) The Drag.Move instance that was created.

Example:

var myDrag = $('myElement').makeDraggable({

    onComplete: function(){

        alert('done dragging');

    }

});

See Also:

§ Drag, Drag.Move

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'

RGB and HSB Representation:

[255255255]

//Or:

[2552552551] //(For transparency.)

Returns:

§ (array) A new Color instance.

Examples:

var black = new Color('#000');

var purple = new Color([255,0,255]);

Notes:

§ For HSB colors, you need to specify the second argument.

Color Method: mix

Mixes two or more colors with the Color.

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:

§ (array) A new Color instance.

Examples:

// mix black with white and purple, each time at 10% of the new color

var darkpurple = new Color('#000').mix('#fff'[2550255]10);

 

$('myDiv').setStyle('background-color', darkpurple);

Color Method: invert

Inverts the Color.

Syntax:

var myInvert = myColor.invert();

Returns:

§ (array) A new Color instance.

Examples:

var white = new Color('#fff');

var black = white.invert();

Color Method: setHue

Modifies the hue of the Color, and returns a new one.

Syntax:

var hue = myColor.setHue(value);

Arguments:

1. value - (number) The hue to set.

Returns:

§ (arrays) A new Color instance.

Example:

var myColor = new Color('#f00');

var myElement = $('myElement');

 

(function(){

    myElement.setStyle('color', myColor.setHue(myColor.hsb[0]++)));

}).periodical(250);

Color Method: setSaturation

Changes the saturation of the Color, and returns a new one.

Syntax:

var saturate = myColor.setSaturation(percent);

Arguments:

1. percent - (number) The percentage of the saturation to set.

Returns:

§ (array) A new Color instance.

Examples:

var myColor = new Color('#f00');

$('myElement').addEvent('mouseenter'function(){

    this.setStyle('background-color', myColor.setSaturation(myColor.hsb[1]++));

});

Color Method: setBrightness

Changes the brightness of the Color, and returns a new one.

Syntax:

var brighten = myColor.setBrightness(percent);

Arguments:

1. percent - (number) The percentage of the brightness to set.

Returns:

§ (array) A new Color instance.

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:

§ (array) A new Color instance.

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.

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:

§ (array) A new Color instance.

Examples:

var myColor = $HSB(5050100);

Native: Array

Contains Array prototypes.

See Also:

§ MDC Array

Array Method: rgbToHsb

Converts a RGB array to an HSB array.

Syntax:

var myHSB = myRGBArray.rgbToHsb();

Returns:

§ (array) An array with HSB values.

Example:

var myHSB = [25500].rgbToHsb()//Returns [0, 100, 100].

Array Method: hsbToRgb

Converts an HSB array to a RGB array.

Syntax:

var myHSB = myRGBArray.hsbToRgb();

Returns:

§ (array) An array with RGB values.

Examples:

var myRGB = [0100100].hsbToRgb()//myRGB = [255, 0, 0]

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:

§ (object) A new Group instance.

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('complete'function(){

    alert('All Scripts loaded');

});

 

xhr1.request();

xhr2.request();

xhr3.request();

Group Method: addEvent

Adds an Event to the stack of Events of the Class instances.

Syntax:

myGroup.addEvent(type, fn);

Arguments:

1. type - (string) The event name (e.g. 'complete') to add.

2. fn - (function) The callback function to execute when all instances fired this event.

Returns:

§ (object) This Group instance.

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

});

See Also:

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:

§ (object) A new Hash.Cookie instance.

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?

See Also:

§ Hash

Hash.Cookie Method: save

Saves the Hash to the cookie. If the hash is empty, removes the cookie.

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'[479]

});

login.set('last_message''User logged in!');

 

login.save()// finally save the Hash

Hash.Cookie Method: load

Loads the cookie and assigns it to the Hash.

Syntax:

myHashCookie.load();

Returns:

§ (object) This Hash.Cookie instance.

Examples:

var myHashCookie = new Hash.Cookie('myCookie');

 

(function(){

    myHashCookie.load();

    if(!myHashCookie.length) alert('Cookie Monster must of eaten it!');

}).periodical(5000);

Notes:

§ Useful when polling.

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.

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

§ start - function executed when the item starts dragging

§ sort - function executed when the item is inserted into a new place in one of the lists

§ complete - 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)

Sortables Method: attach

Attaches the mouse listener to all the handles, enabling sorting.

Syntax:

mySortables.attach();

Returns:

§ (object) This Sortables instance.

Sortables Method: detach

Detaches the mouse listener from all the handles, disabling sorting.

Syntax:

mySortables.detach();

Returns:

§ (object) This Sortables instance.

Sortables Method: addItems

Allows one or more items to be added to an existing Sortables instance.

Syntax:

mySortables.addItems(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:

§ (object) This Sortables instance.

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

Sortables Method: removeItems

Allows one or more items to be removed from an existing Sortables instance.

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:

§ (Elements) An Elements collection of all the elements that were removed.

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

Sortables Method: addLists

Allows one or more entire lists to be added to an existing Sortables instance, allowing sorting between the new and old lists.

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:

§ (object) This Sortables instance.

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

Sortables Method: removeLists

Allows one or more entire lists to be removed from an existing Sortables instance, preventing sorting between the lists.

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:

§ (Elements) An Elements collection of all the lists that were removed.

Examples:

var mySortables = new Sortables('#list1, #list2');

mySortables.removeLists($('list2'));

See Also:

§ Sortables:addLists, Sortables:removeItems

Sortables Method: serialize

Function to get the order of the elements in the lists of this sortables instance. For each list, an array containing the order of the elements will be returned. If more than one list is being used, all lists will be serialized and returned in an array.

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

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(2function(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'

Class: Tips

Display a tip on any element with a title and/or href.

Credits:

§ The idea behind Tips.js is based on Bubble Tooltips by Alessandro Fulcitiniti

Note:

§ Tips requires the page to be in Standards Mode.

Implements:

§ Events, Options

Tips Method: constructor

Arguments:

§ 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 show event is fired.

§ hideDelay - (number: defaults to 100) The delay the hide hide is fired.

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

§ show: fires when the tip is shown

§ hide: fires when the tip is being hidden

Example:

HTML:

<a href="http://mootools.net" title="mootools homepage" class="thisisatooltip" />

JavaScript

var myTips = new Tips('.thisisatooltip');

Tips Event: show

§ (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('show'function(tip){

    tip.fade('in');

});

Tips Event: hide

§ (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('hide'function(tip){

    tip.fade('out');

});

Tips Method: attach

Attaches tooltips to elements. Useful to add more elements to a tips instance.

Syntax:

myTips.attach(elements);

Arguments:

1. elements - (mixed) A collection of elements, a string Selector, or an Element to apply the tooltips to.

Returns:

§ (object) This Tips instance.

Example:

myTips.attach('a.thisisatip');

Tips Method: detach

Detaches tooltips from elements. Useful to remove elements from a tips instance.

Syntax:

myTips.detach(elements);

Arguments:

1. elements - (mixed) A collection of elements, a string Selector, or an Element to apply the tooltips to.

Returns:

§ (object) This Tips instance.

Example:

myTips.detach('a.thisisatip');

Tips HTML Structure

<div class="options.className"//the className you pass in options will be assigned here.

    <div class="tip-top"></div> //useful for styling

 

    <div class="tip">

 

        <div class="tip-title"></div>

 

        <div class="tip-text"></div>

 

    </div>

 

    <div class="tip-bottom"></div> //useful for styling

</div>

Tips with storage

You can also assign tips titles and contents via Element Storage.

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.

Class: SmoothScroll

Auto targets all the anchors in a page and display a smooth scrolling effect upon clicking them.

Note:

§ SmoothScroll requires the page to be in Standards Mode.

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:

§ (object) A new SmoothScroll instance.

Examples:

var mySmoothScroll = new SmoothScroll({

    links: '.smoothAnchors',

    wheelStops: false

});

See Also:

§ Fx.Scroll

Class: Slider

Creates a slider with two elements: a knob and a container.

Note:

§ Slider requires the page to be in Standards Mode.

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.

Slider Event: change

§ (function) Fires when the Slider's value changes.

Signature:

onChange(step)

Arguments:

1. step - (number) The current step that the Slider is on.

Slider Event: onComplete

§ (function) Fire when you're done dragging.

Signature:

onComplete(step)

Arguments:

1. step - (string) The current step that the Slider is on as a string.

Slider Event: tick

§ (function) Fires when the user drags the knob. This Event can be overriden to alter the tick behavior.

Signature:

onTick(pos)

Arguments:

1. pos - (number) The current position that slider moved to.

Notes:

§ Slider originally uses the 'tick' event to set the style of the knob to a new position.

Returns:

§ (object) A new Slider instance.

Examples:

var mySlider = new Slider('myElement''myKnob'{

    range: [-5050],

    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.property, pos);

    },

    onComplete: function(){

        this.element.tween('border').start('#000');

    }

});

Slider Method: set

The slider will move to the passed position.

Syntax:

mySlider.set(step);

Arguments:

1. step - (number) A number to position the Slider to.

Returns:

§ (object) This Slider instance.

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.

Hash: Assets

Provides methods for the dynamic loading and management of JavaScript, CSS, and image files.

Assets Method: javascript

Injects a script tag into the head section of the document, pointing to the src specified.

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:

§ (element) A new script Element.

Examples:

var myScript = new Asset.javascript('/scripts/myScript.js'{id: 'myScript'});

Assets Method: css

Injects a css file in the page.

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:

§ (element) A new link Element.

Examples:

var myCSS = new Asset.css('/css/myStyle.css'{id: 'myStyle', title: 'myStyle'});

Assets Method: image

Preloads an image and returns the img element.

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:

§ (element) A new HTML img Element.

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.

Assets Method: images

Preloads an array of images (as strings) and returns an array of img elements. does not inject them to the page.

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.

Options:

onComplete

§ (function) Executes when all image files are loaded.

Signature:

onComplete()

onProgress

§ (function) Executes when one image file is loaded.

Signature:

onProgress(counter, index)

Arguments:

1. counter - (number) The number of loaded images.

2. index - (number) The index of the loaded image.

Returns:

§ (array) An Elements collection.

Examples:

var myImages = new Asset.images(['/images/myImage.png''/images/myImage2.gif']{

    onComplete: function(){

        alert('All images loaded!');

    }

});

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:

§ (object) A new Accordion instance.

Events:

active

§ (function) Function to execute when an element starts to show.

Signature:

onActive(toggler, element)

Arguments:

1. toggler - (element) The toggler for the Element being displayed.

2. element - (element) The Element being displayed.

background

§ (function) Function to execute when an element starts to hide.

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

Accordion Method: addSection

Dynamically adds a new section into the Accordion at the specified position.

Syntax:

myAccordion.addSection(toggler, element[, pos]);

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:

§ (object) This Accordion instance.

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.

Accordion Method: display

Shows a specific section and hides all others. Useful when triggering an accordion from outside.

Syntax:

myAccordion.display(index);

Arguments:

1. index - (mixed) The index of the item to show, or the actual element to be displayed.

Returns:

§ (object) This Accordion instance.

Examples:

// Make a ticker-like accordion. Kids don't try this at home.

var myAccordion = new Accordion('.togglers''.elements'{

    onComplete: function(){

        this.display.delay(2500this(this.previous + 1) % this.togglers.length);

    }

});