Core contains an handful of common sense functions used in MooTools. It also contains some basic Hash and Array methods.
Checks to see if a value exists or is 0. Useful for allowing 0.
$chk(item);
1. item - (mixed) The item to inspect.
§ (boolean) If the object passed in exists or is 0, returns true. Otherwise, returns false.
function myFunction(arg){
if($chk(arg)) alert('The object exists or is 0.');
else alert('The object is either null, undefined, false, or ""');
}
Clears a Timeout or an Interval. Useful when working with Function:delay andFunction:periodical.
$clear(timer);
1. timer - (number) The identifier of the setInterval (periodical) or setTimeout (delay) to clear.
§ (null) returns null.
var myTimer = myFunction.delay(5000); //Waits 5 seconds then executes myFunction.
myTimer = $clear(myTimer); //Cancels myFunction.
§ Function:delay
§ Function:periodical
Checks to see if a value is defined.
$defined(obj);
1. obj - (mixed) The object to inspect.
§ (boolean) If the object passed is not null or undefined, returns true. Otherwise, returns false.
function myFunction(arg){
if($defined(arg)) alert('The object is defined.');
else alert('The object is null or undefined.');
}
Creates a function which returns the passed argument according to the index (i) passed.
var argument = $arguments(i);
1. i - (number) The index of the argument to return.
§ (function) The function that returns a certain argument from the function's arguments.
var secondArgument = $arguments(1);
alert(secondArgument('a','b','c')); //Alerts "b".
An empty function, that's it. Typically used for as a placeholder inside event methods of classes.
var emptyFn = $empty;
var myFunc = $empty;
Creates an empty function which does nothing but return the value passed.
var returnTrue = $lambda(true);
1. value - (mixed) The value for the created function to return.
§ (function) A function which returns the desired value.
myLink.addEvent('click', $lambda(false)); //Prevents a link Element from being clickable.
Copies all the properties from the second object passed in to the first object passed in.
$extend(original, extended);
1. original - (object) The object to be extended.
2. extension - (object) The object whose properties will be copied to original.
§ (object) The first object passed in, extended.
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'};
Merges any number of objects recursively without referencing them or their sub-objects.
var merged = $merge(obj1, obj2[, obj3[, ...]]);
1. (objects) Any number of objects.
§ (object) The object that is created as a result of merging all the objects passed in.
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}}
Used to iterate through iterables that are not regular arrays, such as built in getElementsByTagName calls, arguments of a function, or an object.
$each(iterable, fn[, bind]);
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.
fn(item, index, object)
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.
$each(['Sun','Mon','Tue'], function(day, index){
alert('name:' + day + ', index: ' + index);
}); //Alerts "name: Sun, index: 0", "name: Mon, index: 1", etc.
//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);
});
Returns the first defined argument passed in, or null.
var picked = $pick(var1[, var2[, var3[, ...]]]);
§ (mixed) Any number of variables.
§ (mixed) The first variable that is defined.
§ (null) If all variables passed in are null or undefined, returns null.
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."
Returns a random integer between the two passed in values.
var random = $random(min, max);
1. min - (number) The minimum value (inclusive).
2. max - (number) The maximum value (inclusive).
§ (number) A random number between min and max.
alert($random(5, 20)); //Alerts a random number between 5 and 20.
Converts the argument passed in to an array if it is defined and not already an array.
var splatted = $splat(obj);
1. obj - (mixed) Any type of variable.
§ (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.
$splat('hello'); //Returns ['hello'].
$splat(['a', 'b', 'c']); //Returns ['a', 'b', 'c'].
Returns the current time as a timestamp.
var time = $time();
§ (number) - The current timestamp.
Tries to execute a number of functions. Returns immediately the return value of the first non-failed function without executing successive functions, or null.
$try(fn[, fn, fn, fn, ...]);
§ fn - (function) The function to execute.
§ (mixed) Standard return of the called function.
§ (null) null if all the passed functions fail.
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!');
Returns the type of object that matches the element passed in.
$type(obj);
1. obj - (object) The object to inspect.
§ '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.
var myString = 'hello';
$type(myString); //Returns "string".
Some browser properties are attached to the Browser Object for browser and platform detection.
§ 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.
§ 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.
§ 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.
§ Engine detection is entirely feature-based.
A collection of Array methods.
§ MDC Array
Calls a function for each element in the array.
myArray.each(fn[, bind]);
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.
fn(item, index, array)
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.
//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.
§ MDC Array:forEach
§ This method is only available for browsers without native MDC Array:forEach support.
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.
var allPassed = myArray.every(fn[, bind]);
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.
fn(item, index, array)
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.
§ (boolean) If every element in the array satisfies the provided testing function, returns true. Otherwise, returns false.
var areAllBigEnough = [10, 4, 25, 100].every(function(item, index){
return item > 20;
}); //areAllBigEnough = false
§ MDC Array:every
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.
var filteredArray = myArray.filter(fn[, bind]);
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.
fn(item, index, array)
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.
§ (array) The new filtered array.
var biggerThanTwenty = [10, 3, 25, 100].filter(function(item, index){
return item > 20;
}); //biggerThanTwenty = [25, 100]
§ MDC Array:filter
Creates a new array with all of the elements of the array which are defined (i.e. not null or undefined).
var cleanedArray = myArray.clean();
§ (array) The new filtered array.
var myArray = [null, 1, 0, true, false, "foo", undefined, ""];
myArray.clean() // returns [1, 0, true, false, "foo", ""]
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.
var index = myArray.indexOf(item[, from]);
§ (number) The index of the first element within the array equal to the specified value. If not found, returns -1.
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.
['apple', 'lemon', 'banana'].indexOf('lemon'); //returns 1
['apple', 'lemon'].indexOf('banana'); //returns -1
§ MDC Array:indexOf
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.
var mappedArray = myArray.map(fn[, bind]);
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.
fn(item, index, array)
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.
§ (array) The new mapped array.
var timesTwo = [1, 2, 3].map(function(item, index){
return item * 2;
}); //timesTwo = [2, 4, 6];
§ MDC Array:map
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.
var somePassed = myArray.some(fn[, bind]);
§ (boolean) If at least one element in the array satisfies the provided testing function returns true. Otherwise, returns false.
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.
fn(item, index, array)
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.
var isAnyBigEnough = [10, 4, 25, 100].some(function(item, index){
return item > 20;
}); //isAnyBigEnough = true
§ MDC Array:some
Creates an object with key-value pairs based on the array of keywords passed in and the current content of the array.
var associated = myArray.associate(obj);
1. obj - (array) Its items will be used as the keys of the object that will be created.
§ (object) The new associated object.
var animals = ['Cow', 'Pig', 'Dog', 'Cat'];
var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
sounds.associate(animals);
//returns {'Cow': 'Moo', 'Pig': 'Oink', 'Dog': 'Woof', 'Cat': 'Miao'}
Accepts an object of key / function pairs to assign values.
var result = Array.link(array, object);
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.
§ (object) The new associated object.
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}
Tests an array for the presence of an item.
var inArray = myArray.contains(item[, from]);
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.
§ (boolean) If the array contains the item specified, returns true. Otherwise, returns false.
["a","b","c"].contains("a"); //returns true
["a","b","c"].contains("d"); //returns false
§ MDC Array:indexOf
Extends an array with all the items of another.
myArray.extend(array);
1. array - (array) The array whose items should be extended into this array.
§ (array) This array, extended.
var animals = ['Cow', 'Pig', 'Dog'];
animals.extend(['Cat', 'Dog']); //animals = ['Cow', 'Pig', 'Dog', 'Cat', 'Dog'];
Returns the last item from the array.
myArray.getLast();
§ (mixed) The last item in this array.
§ (null) If this array is empty, returns null.
['Cow', 'Pig', 'Dog', 'Cat'].getLast(); //returns 'Cat'
Returns a random item from the array.
myArray.getRandom();
§ (mixed) A random item from this array. If this array is empty, returns null.
['Cow', 'Pig', 'Dog', 'Cat'].getRandom(); //returns one of the items
Pushes the passed element into the array if it's not already present (case and type sensitive).
myArray.include(item);
1. item - (object) The item that should be added to this array.
§ (array) This array with the new item included.
['Cow', 'Pig', 'Dog'].include('Cat'); //returns ['Cow', 'Pig', 'Dog', 'Cat']
['Cow', 'Pig', 'Dog'].include('Dog'); //returns ['Cow', 'Pig', 'Dog']
Combines an array with all the items of another. Does not allow duplicates and is case and type sensitive.
myArray.combine(array);
1. array - (array) The array whose items should be combined into this array.
§ (array) This array combined with the new items.
var animals = ['Cow', 'Pig', 'Dog'];
animals.combine(['Cat', 'Dog']); //animals = ['Cow', 'Pig', 'Dog', 'Cat'];
Removes all occurrences of an item from the array.
myArray.erase(item);
1. item - (object) The item to search for in the array.
§ (array) This array with all occurrences of the item removed.
['Cow', 'Pig', 'Dog', 'Cat', 'Dog'].erase('Dog') //returns ['Cow', 'Pig', 'Cat']
['Cow', 'Pig', 'Dog'].erase('Cat') //returns ['Cow', 'Pig', 'Dog']
Empties an array.
myArray.empty();
§ (array) This array, emptied.
var myArray = ['old', 'data'];
myArray.empty(); //myArray is now []
Flattens a multidimensional array into a single array.
myArray.flatten();
§ (array) A new flat array.
var myArray = [1,2,3,[4,5, [6,7]], [[[8]]]];
var newArray = myArray.flatten(); //newArray is [1,2,3,4,5,6,7,8]
Converts an hexidecimal color value to RGB. Input array must be the following hexidecimal color format. ['FF','FF','FF']
myArray.hexToRgb([array]);
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)").
§ (string) A string representing the color in RGB.
§ (array) If the array flag is set, an array will be returned instead.
['11','22','33'].hexToRgb(); //returns "rgb(17,34,51)"
['11','22','33'].hexToRgb(true); //returns [17, 34, 51]
§ String:hexToRgb
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]
myArray.rgbToHex([array]);
1. array - (boolean, optional) If true is passed, will output an array (eg. ['ff','33','00']) instead of a string (eg. "#ff3300").
§ (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.
[17,34,51].rgbToHex(); //returns "#112233"
[17,34,51].rgbToHex(true); //returns ['11','22','33']
[17,34,51,0].rgbToHex(); //returns "transparent"
§ String:rgbToHex
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.
var copiedArray = $A(iterable);
1. iterable - (array) The iterable to copy.
§ (array) The new copied array.
function myFunction(){
$A(arguments).each(function(argument, index){
alert(argument);
});
};
myFunction("One", "Two", "Three"); //Alerts "One", then "Two", then "Three".
var anArray = [0, 1, 2, 3, 4];
var copiedArray = $A(anArray); //Returns [0, 1, 2, 3, 4].
each
every
filter
clean
indexOf
map
some
associate
link
contains
extend
getLast
getRandom
include
combine
erase
empty
flatten
hexToRgb
rgbToHex
A
Function Methods.
§ MDC Function
Base function for creating functional closures which is used by all other Function prototypes.
var createdFunction = myFunction.create([options]);
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.
§ 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.
§ (function) The function that was created as a result of the options passed in.
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
});
Returns a closure with arguments and bind.
var newFunction = myFunction.pass([args[, bind]]);
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.
§ (function) The function whose arguments are passed when called.
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.
Tries to execute the function.
var result = myFunction.attempt([args[, bind]]);
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.
§ (mixed) The function's return value or null if an exception is thrown.
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
Changes the scope of this within the target function to refer to the bind parameter.
myFunction.bind([bind[, args[, evt]]]);
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).
§ (function) The bound function.
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.
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.
myFunction.bindWithEvent([bind[, args[, evt]]]);
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).
§ (function) The bound function.
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.
Delays the execution of a function by a specified duration.
var timeoutID = myFunction.delay([delay[, bind[, args]]]);
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).
§ (number) The JavaScript timeout id (for clearing delays).
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);
§ $clear, MDC setTimeout
Executes a function in the specified intervals of time. Periodic execution can be stopped using the $clear function.
var intervalID = myFunction.periodical([period[, bind[, args]]]);
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).
§ (number) The Interval id (for clearing a periodical).
var Site = { counter: 0 };
var addCount = function(){ this.counter++; };
addCount.periodical(1000, Site); //Will add the number of seconds at the Site.
§ $clear, MDC setInterval
Runs the Function with specified arguments and binding. The same as apply but reversed and with support for a single argument.
var myFunctionResult = myFunction.run(args[, bind]);
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.
§ (mixed) This Function's return value.
var myFn = function(a, b, c){
return a + b + c;
}
var myArgs = [1,2,3];
myFn.run(myArgs); //Returns: 6
var myFn = function(a, b, c) {
return a + b + c + this;
}
var myArgs = [1,2,3];
myFn.run(myArgs, 6); //Returns: 12
A collection of the Number Object methods.
§ MDC Number
Every Math method is mirrored in the Number object, both as prototype and generic.
Limits this number between two bounds.
myNumber.limit(min, max);
1. min - (number) The minimum possible value.
2. max - (number) The maximum possible value.
§ (number) The number bounded between the given limits.
(12).limit(2, 6.5); //Returns: 6.5
(-4).limit(2, 6.5); //Returns: 2
(4.3).limit(2, 6.5); //Returns: 4.3
Returns this number rounded to the specified precision.
myNumber.round([precision]);
1. precision - (number, optional: defaults to 0) The number of digits after the decimal place.
§ (number) The number, rounded.
§ Argument may also be negative.
(12.45).round() //Returns: 12
(12.45).round(1) //Returns: 12.5
(12.45).round(-1) //Returns: 10
Executes the function passed in the specified number of times.
myNumber.times(fn[, bind]);
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.
(4).times(alert); //Alerts "0", then "1", then "2", then "3".
Returns this number as a float. Useful because toFloat must work on both Strings and Numbers.
myNumber.toFloat();
§ (number) The number as a float.
(111).toFloat(); //returns 111
(111.1).toFloat(); //returns 111.1
Returns this number as another number with the passed in base. Useful because toInt must work on both Strings and Numbers.
myNumber.toInt([base]);
1. base - (number, optional: defaults to 10) The base to use.
§ (number) A number with the base provided.
(111).toInt(); //returns 111
(111.1).toInt(); //returns 111
(111).toInt(2); //returns 7
A collection of the String Object prototype methods.
§ MDC String
Searches for a match between the string and a regular expression. For more information seeMDC Regexp:test.
myString.test(regex[,params]);
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).
§ (boolean) true, if a match for the regular expression is found in this string.
§ (boolean) false if is not found
"I like cookies".test("cookie"); //returns true
"I like cookies".test("COOKIE", "i"); //returns true (ignore case)
"I like cookies".test("cake"); //returns false
§ MDC Regular Expressions
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.
myString.contains(string[, separator]);
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 ' ').
§ (boolean) true if the string is contained in this string
§ (boolean) false if not.
'a bc'.contains('bc'); //returns true
'a b c'.contains('c', ' '); //returns true
'a bc'.contains('b', ' '); //returns false
Trims the leading and trailing spaces off a string.
myString.trim();
§ (string) The trimmed string.
" i like cookies ".trim(); //"i like cookies"
Removes all extraneous whitespace from a string and trims it (String:trim).
myString.clean();
§ (string) The cleaned string.
" i like cookies \n\n".clean(); //returns "i like cookies"
Converts a hyphenated string to a camelcased string.
myString.camelCase();
§ (string) The camelcased string.
"I-like-cookies".camelCase(); //returns "ILikeCookies"
Converts a camelcased string to a hyphenated string.
myString.hyphenate();
§ (string) The hyphenated string.
"ILikeCookies".hyphenate(); //returns "I-like-cookies"
Converts the first letter of each word in a string to uppercase.
myString.capitalize();
§ (string) The capitalized string.
"i like cookies".capitalize(); //returns "I Like Cookies"
Escapes all regular expression characters from the string.
myString.escapeRegExp();
§ (string) The escaped string.
'animals.sheep[1]'.escapeRegExp(); //returns 'animals\.sheep\[1\]'
Parses this string and returns a number of the specified radix or base.
myString.toInt([base]);
1. base - (number, optional) The base to use (defaults to 10).
§ (number) The number.
§ (NaN) If the string is not numeric, returns NaN.
"4em".toInt(); //returns 4
"10px".toInt(); //returns 10
§ MDC parseInt
Parses this string and returns a floating point number.
myString.toFloat();
§ (number) The float.
§ (NaN) If the string is not numeric, returns NaN.
"95.25%".toFloat(); //returns 95.25
"10.848".toFloat(); //returns 10.848
§ MDC parseFloat
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'
myString.hexToRgb([array]);
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)").
§ (string) A string representing the color in RGB.
§ (array) If the array flag is set, an array will be returned instead.
"#123".hexToRgb(); //returns "rgb(17,34,51)"
"112233".hexToRgb(); //returns "rgb(17,34,51)"
"#112233".hexToRgb(true); //returns [17, 34, 51]
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)"
myString.rgbToHex([array]);
1. array - (boolean, optional) If true is passed, will output an array (eg. ['ff','33','00']) instead of a string (eg. "#ff3300").
§ (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.
"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"
§ Array:rgbToHex
Strips the String of its <script> tags and anything in between them.
myString.stripScripts([evaluate]);
1. evaluate - (boolean, optional) If true is passed, the scripts within the String will be evaluated.
§ (string) - The String without the stripped scripts.
var myString = "<script>alert('Hello')</script>Hello, World.";
myString.stripScripts(); //Returns "Hello, World."
myString.stripScripts(true); //Alerts "Hello", then returns "Hello, World."
Substitutes keywords in a string using an object/array. Removes undefined keywords and ignores escaped keywords.
myString.substitute(object[, regexp]);
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 .
§ (string) - The substituted string.
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
test
contains
trim
clean
camelCase
hyphenate
capitalize
escapeRegExp
toInt
toFloat
hexToRgb
rgbToHex
stripScripts
substitute
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!
var myHash = new Hash([object]);
1. object - (mixed) A hash or object to implement.
§ (hash) A new Hash instance.
var myHash = new Hash({
aProperty: true,
aMethod: function(){
return true;
}
});
alert(myHash.has('aMethod')); //Returns true.
Calls a function for each key-value pair in the object.
myHash.each(fn[, bind]);
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.
fn(value, key, hash)
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.
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.
Tests for the presence of a specified key in the Hash.
var inHash = myHash.has(item);
1. key - (string) The key to search for in the Hash.
§ (boolean) If the Hash has a defined value for the specified key, returns true. Otherwise, returns false.
var hash = new Hash({'a': 'one', 'b': 'two', 'c': 'three'});
hash.has('a'); //returns true
hash.has('d'); //returns false
§ Testing for a Hash prototype will never return true. Only testing the actual properties of the Hash will return true.
Returns the key of the specified value. Synonymous with Array:indexOf.
var key = myHash.keyOf(item);
1. item - (mixed) The item to search for in the Hash.
§ (string) If the Hash has a the specified item in it, returns the key of that item.
§ (boolean) Otherwise, returns false.
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
§ Testing for a Hash prototype will never return its key. Only the actual properties of the Hash will return their associated key.
Tests for the presence of a specified value in the Hash.
var inHash = myHash.hasValue(value);
1. value - (mixed) The value to search for in the Hash.
§ (boolean) If the Hash has the passed in value in any of the keys, returns true. Otherwise, returns false.
var hash = new Hash({'a': 'one', 'b': 'two', 'c': 'three'});
hash.hasValue('one'); //returns true
hash.hasValue('four'); //returns false
Extends this Hash with the key-value pairs from the object passed in.
myHash.extend(properties);
1. properties - (object) The object whose items should be extended into this Hash
§ (hash) This Hash, extended.
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' };
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.
myHash.combine(properties);
1. properties - (object) The object whose items should be combined into this Hash.
§ (hash) This Hash, combined with the new key-value pairs.
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' };
Removes the specified key from the Hash.
myHash.erase(key);
1. key - (string) The key to search for in the Hash.
§ (hash) This Hash with the specified key and its value removed.
var hash = new Hash({
'name': 'John',
'lastName': 'Doe'
});
hash.erase('lastName');
//hash now holds an object containing: { 'name': 'John' };
Retrieves a value from the hash.
myHash.get(key);
1. key - (string) The key to retrieve in the Hash.
§ (mixed) Returns the value that corresponds to the key if found.
§ (null) null if the key doesn't exist.
var hash = new Hash({
'name': 'John',
'lastName': 'Doe'
});
hash.get('name'); //returns 'John'
Adds a key-value pair to the hash or replaces a previous value associated with the specified key.
myHash.set(key, value);
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.
§ (hash) This Hash with the specified key set to the specified value.
var hash = new Hash({
'name': 'John',
'lastName': 'Doe'
});
hash.set('name', 'Michelle'); //hash.name is now 'Michelle'
Empties the hash.
myHash.empty();
var hash = new Hash({
'name': 'John',
'lastName': 'Doe'
});
hash.empty();
//hash now holds an empty object: {}
Includes the specified key-value pair in the Hash if the key doesn't already exist.
myHash.include(key, value);
1. key - (string) The key to insert into the Hash.
2. value - (mixed) The value to associate with the specified key in the Hash.
§ (hash) This Hash with the specified key included if it did not previously exist.
var hash = new Hash({
'name': 'John',
'lastName': 'Doe'
});
hash.include('name', 'Michelle'); //hash is unchanged
hash.include('age', 25); //hash.age is now 25
Creates a new map with the results of calling a provided function on every value in the map.
var mappedHash = myHash.map(fn[, bind]);
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.
fn(value, key, hash)
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.
§ (hash) The new mapped hash.
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};
Creates a new Hash with all of the elements of the Hash for which the provided filtering function returns true.
var filteredHash = myHash.filter(fn[, bind]);
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.
fn(value, key, hash)
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.
§ (hash) The new filtered hash.
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}
Returns true if every value in the object satisfies the provided testing function.
var allPassed = myHash.every(fn[, bind]);
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].
fn(value, key, hash)
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.
§ (boolean) If every value in the Hash satisfies the provided testing function, returns true. Otherwise, returns false.
var areAllBigEnough = ({a: 10, b: 4, c: 25, d: 100}).every(function(value, key){
return value > 20;
}); //areAllBigEnough = false
Returns true if at least one value in the object satisfies the provided testing function.
var anyPassed = myHash.any(fn[, bind]);
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.
fn(value, key, hash)
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.
§ (boolean) If any value in the Hash satisfies the provided testing function, returns true. Otherwise, returns false.
var areAnyBigEnough = ({a: 10, b: 4, c: 25, d: 100}).some(function(value, key){
return value > 20;
}); //isAnyBigEnough = true
Returns a a clean object from an Hash.
myHash.getClean();
§ (object) a clean object
var hash = new Hash({
'name': 'John',
'lastName': 'Doe'
});
hash = hash.getClean(); // hash doesnt contain Hash prototypes anymore
hash.each() //error!
Returns an array containing all the keys, in the same order as the values returned byHash:getValues.
var keys = myHash.getKeys();
§ (array) An array containing all the keys of the hash.
Returns an array containing all the values, in the same order as the keys returned byHash:getKeys.
var values = myHash.getValues();
§ (array) An array containing all the values of the hash.
Returns the number of keys in the Hash.
var length = myHash.getLength();
§ (number) The length of the Hash.
var hash = new Hash({
'name': 'John',
'lastName': 'Doe'
});
hash.getLength(); // returns 2
Generates a query string from key/value pairs in an object and URI encodes the values.
var queryString = myHash.toQueryString();
1. source - (object) The object to generate the query string from.
§ (string) The query string.
Hash.toQueryString({apple: "red", lemon: "yellow"}); //returns "apple=red&lemon=yellow"
var myHash = new Hash({apple: "red", lemon: "yellow"});
myHash.toQueryString(); //returns "apple=red&lemon=yellow"
Shortcut for the new Hash.
§ Hash
constructor
each
has
keyOf
hasValue
extend
combine
erase
get
set
empty
include
map
filter
every
some
getClean
getKeys
getValues
getLength
toQueryString
H
MooTools Event Methods.
new Event([event[, win]]);
1. event - (event) An HTMLEvent Object.
2. win - (window, optional: defaults to window) The context of the event.
§ 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 $.
$('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.
});
§ 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.
Stop an Event from propagating and also executes preventDefault.
myEvent.stop();
§ (object) This Event instance.
<a id="myAnchor" href="http://google.com/">Visit Google.com</a>
$('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(500, this);
});
§ Returning false within the function can also stop the propagation of the Event.
§ Element.addEvent, Element.stopPropagation, Event.preventDefault, Function:delay
Cross browser method to stop the propagation of an event (this stops the event from bubbling up through the DOM).
myEvent.stopPropagation();
§ (object) This Event object.
"#myChild" does not cover the same area as myElement. Therefore, the 'click' differs from parent and child depending on the click location:
<div id="myElement">
<div id="myChild"></div>
</div>
$('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.
});
§ Element:addEvent
§ MDC event.stopPropagation
Cross browser method to prevent the default action of the event.
myEvent.preventDefault();
§ (object) This Event object.
<form>
<input id="myCheckbox" type="checkbox" />
</form>
$('myCheckbox').addEvent('click', function(event){
event.preventDefault(); //Will prevent the checkbox from being "checked".
});
§ Element:addEvent
§ MDC event.preventDefault
Additional Event key codes can be added by adding properties to the Event.Keys Hash.
Event.Keys.shift = 16;
$('myInput').addEvent('keydown', function(event){
if (event.key == "shift") alert("You pressed shift.");
});
The base Class of the MooTools framework.
var MyClass = new Class(properties);
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).
§ (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.
§ (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.
§ (function) The initialize function will be the constructor for this class when new instances are created.
§ (class) The created Class.
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.
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.
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'.
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.
MyClass.implement(properties);
1. properties - (object) The properties to add to the base Class.
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'
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.
var MyClass = new Class({ Implements: Chain });
MyClass.implement(Chain);
var myChain = new Chain;
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'); }
);
§ Class
Adds functions to the end of the call stack of the Chain instance.
myClass.chain(fn[, fn2[, fn3[, ...]]]);
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.
§ (object) The current Class instance. Calls to chain can also be chained.
//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.
§ Fx, Fx.Tween
Removes the first function of the Chain instance stack and executes it. The next function will then become first in the array.
myClass.callChain([any arguments]);
1. Any arguments passed in will be passed to the "next" function.
§ (mixed) The return value of the "next" function or false when the chain was empty.
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'.
Clears the stack of a Chain instance.
myClass.clearChain();
§ (object) The current Class instance.
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.
§ Fx, Fx.Tween
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.
var MyClass = new Class({ Implements: Events });
MyClass.implement(Events);
§ 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).
var Widget = new Class({
Implements: Events,
initialize: function(element){
// ...
},
complete: function(){
this.fireEvent('complete');
}
});
var myWidget = new Widget();
myWidget.addEvent('complete', myFunction);
§ Events starting with 'on' are still supported in all methods and are converted to their representation without 'on' (e.g. 'onComplete' becomes 'complete').
§ Class, Options
Adds an event to the Class instance's event stack.
myClass.addEvent(type, fn[, internal]);
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.
§ (object) This Class instance.
var myFx = new Fx.Tween('element', 'opacity');
myFx.addEvent('start', myStartFunction);
The same as addEvent, but accepts an object to add multiple events at once.
myClass.addEvents(events);
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.
§ (object) This Class instance.
var myFx = new Fx.Tween('element', 'opacity');
myFx.addEvents({
'start': myStartFunction,
'complete': function() {
alert('Done.');
}
});
Fires all events of the specified type in the Class instance.
myClass.fireEvent(type[, args[, delay]]);
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).
§ (object) This Class instance.
var Widget = new Class({
Implements: Events,
initialize: function(arg1, arg2){
//...
this.fireEvent("initialize", [arg1, arg2], 50);
}
});
Removes an event from the stack of events of the Class instance.
myClass.removeEvent(type, fn);
1. type - (string) The type of event (e.g. 'complete').
2. fn - (function) The function to remove.
§ (object) This Class instance.
§ If the function has the property internal and is set to true, then the event will not be removed.
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.
myClass.removeEvents([events]);
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.
§ (object) The current Class instance.
var myFx = new Fx.Tween('myElement', 'opacity');
myFx.removeEvents('complete');
§ removeEvents will not remove internal events. See Events:removeEvent.
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).
var MyClass = new Class({Implements: Options});
MyClass.implement(Options);
Merges the default options of the Class with the options passed in.
myClass.setOptions([options]);
1. options - (object, optional) The user defined options to merge with the defaults.
§ (object) The current Class instance.
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}}
§ 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.
The following functions are treated as Window methods.
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.
var myElement = $(el);
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.
§ (element) A DOM element.
§ (null) Null if no matching id was found or if toElement did not return an element.
var myElement = $('myElement');
var div = document.getElementById('myElement');
div = $(div); //The element with all the Element methods applied.
§ 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.
Selects and extends DOM elements. Elements arrays returned with $$ will also accept all theElement methods.
var myElements = $$(aTag[, anElement[, Elements[, ...]);
§ Any number of the following as arguments are accepted:
§ HTMLCollections,
§ arrays of elements,
§ elements, or
§ strings as selectors.
§ (array) - An array of all the DOM elements matched, extended with $.
$$('a'); //Returns all anchor elements in the page.
$$('a', 'b'); //Returns all anchor and bold tags on the page.
$$('#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'.
//Creates an array of all elements and selectors passed as arguments.
$$(myelement1, myelement2, 'a', '#myid, #myid2, #myid3', document.getElementsByTagName('div'));
§ 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 Selectors for documentation on selectors for use anywhere they are accepted throughout the framework.
Custom Native to allow all of its methods to be used with any extended DOM Element.
Creates a new Element of the type passed in.
var myEl = new Element(element[, properties]);
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.
§ (element) A new MooTools extended HTML Element.
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');
}
}
});
§ $, Element:set
Gets the first descendant element whose tag name matches the tag provided. If Selectors is included, CSS selectors may also be passed.
var myElement = myElement.getElement(tag);
1. tag - (string) Tag name of the element to find.
§ (mixed) If a match is found, the Element will be returned. Otherwise, returns null.
var firstDiv = $(document.body).getElement('div');
§ 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 Selectors for documentation on selectors for use anywhere they are accepted throughout the framework.
Collects all decedent elements whose tag name matches the tag provided. If Selectors is included, CSS selectors may also be passed.
var myElements = myElement.getElements(tag);
1. tag - (string) String of the tag to match.
§ (array) An Elements array of all matched Elements.
var allAnchors = $(document.body).getElements('a');
§ 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 Selectors for documentation on selectors for use anywhere they are accepted throughout the framework.
Gets the element with the specified id found inside the current Element.
var myElement = anElement.getElementById(id);
1. id - (string) The ID of the Element to find.
§ (mixed) If a match is found, returns that Element. Otherwise, returns null.
var myChild = $('myParent').getElementById('myChild');
§ This method is not provided for Document instances as document.getElementById is provided natively.
This is a "dynamic arguments" method. Properties passed in can be any of the 'set' properties in the Element.Properties Hash.
myElement.set(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).
§ (element) This Element.
$('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'
});
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'
});
§ 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.
§ Element, Element.Properties, Element:setProperty, Element:addEvents, Element:setStyles
This is a "dynamic arguments" method. Properties passed in can be any of the 'get' properties in the Element.Properties Hash.
myElement.get(property);
1. property - (string) The string key from the Element.Properties Hash representing the property to get.
§ (mixed) The result of calling the corresponding 'get' function in the Element.Properties Hash.
var tag = $('myDiv').get('tag'); //Returns "div".
var id = $('myDiv').get('id'); //Returns "myDiv".
var value = $('myInput').get('value'); //Returns the myInput element's value.
§ If the corresponding accessor doesn't exist in the Element.Properties Hash, the result ofElement:getProperty on the property passed in is returned.
§ Element, Element.Properties, Element:getProperty
This is a "dynamic arguments" method. Properties passed in can be any of the 'erase' properties in the Element.Properties Hash.
myElement.erase(property);
1. property - (string) The string key from the Element.Properties Hash representing the property to erase.
§ (mixed) The result of calling the corresponding 'erase' function in the Element.Properties Hash.
$('myDiv').erase('id'); //Removes the id from myDiv.
$('myDiv').erase('class'); //myDiv element no longer has any class names set.
§ If the corresponding eraser doesn't exist in the Element.Properties Hash, Element:removeProperty is called with the property passed in.
§ Element, Element.Properties, Element:removeProperty
Tests this Element to see if it matches the argument passed in.
myElement.match(match);
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.
§ (boolean) If the element matched, returns true. Otherwise, returns false.
//Returns true if #myDiv is a div.
$('myDiv').match('div');
//Returns true if #myDiv has the class foo and is named "bar"
$('myDiv').match('.foo[name=bar]');
var el = $('myDiv');
$('myDiv').match(el); //Returns true
$('otherElement').match(el); //Returns false
Injects, or inserts, the Element at a particular place relative to the Element's children (specified by the second the argument).
myElement.inject(el[, where]);
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'.
§ (element) This Element.
var myFirstElement = new Element('div', {id: 'myFirstElement'});
var mySecondElement = new Element('div', {id: 'mySecondElement'});
var myThirdElement = new Element('div', {id: 'myThirdElement'});
<div id="myFirstElement"></div>
<div id="mySecondElement"></div>
<div id="myThirdElement"></div>
myFirstElement.inject(mySecondElement);
<div id="mySecondElement">
<div id="myFirstElement"></div>
</div>
myThirdElement.inject(mySecondElement, 'top');
<div id="mySecondElement">
<div id="myThirdElement"></div>
<div id="myFirstElement"></div>
</div>
myFirstElement.inject(mySecondElement, 'before');
<div id="myFirstElement"></div>
<div id="mySecondElement"></div>
myFirstElement.inject(mySecondElement, 'after');
<div id="mySecondElement"></div>
<div id="myFirstElement"></div>
Element:adopt, Element:grab, Element:wraps
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).
myElement.grab(el[, where]);
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'.
§ (element) This Element.
var myFirstElement = new Element('div', {id: 'myFirstElement'});
var mySecondElement = new Element('div', {id: 'mySecondElement'});
myFirstElement.grab(mySecondElement);
<div id="myFirstElement">
<div id="mySecondElement"></div>
</div>
Element:adopt, Element:inject, Element:wraps
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).
myParent.adopt(el[, others]);
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.
§ (element) This Element.
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]);
<div id="myParent">
<div id="myFirstElement" />
</div>
<div id="myParent2">
<div id="myFirstElement" />
<a />
</div>
<div id="myParent3">
<div id="myFirstElement" />
<a />
<ul />
</div>
Element:grab, Element:inject, Element: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.
myParent.wraps(el[, where]);
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'.
§ (element) This Element.
<div id="myFirstElement"></div>
var mySecondElement = new Element('div', {id: 'mySecondElement'});
mySecondElement.wraps($('myFirstElement'));
<div id="mySecondElement">
<div id="myFirstElement"></div>
</div>
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.
myElement.appendText(text);
1. text - (string) The text to append.
2. where - (string, optional: default 'bottom') The position to inject the text to.
§ (element) The current Element instance.
<div id="myElement">Hey.</div>
$('myElement').appendText(' Howdy.');
<div id="myElement">Hey. Howdy.</div>
Removes the Element from the DOM.
var removedElement = myElement.dispose();
§ (element) This Element. Useful to always grab the return from this function, as the element could beinjected back.
<div id="myElement"></div>
<div id="mySecondElement"></div>
$('myElement').dispose();
<div id="mySecondElement"></div>
§ MDC Element:removeChild
Clones the Element and returns the cloned one.
var copy = myElement.clone([contents, keepid]);
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.
§ (element) The cloned Element.
<div id="myElement"></div>
//Clones the Element and appends the clone after the Element.
var clone = $('myElement').clone().injectAfter('myElement');
<div id="myElement">ciao</div>
<div>ciao</div>
§ 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.
§ Element:cloneEvents.
Replaces the Element with an Element passed.
var element = myElement.replaces(el);
1. el - (mixed) A string id representing the Element to be replaced with, or an Element reference.
§ (element) This Element.
$('myNewElement').replaces($('myOldElement'));
//$('myOldElement') is gone, and $('myNewElement') is in its place.
§ MDC Element:replaceChild
Tests the Element to see if it has the passed in className.
var result = myElement.hasClass(className);
1. className - (string) The class name to test.
§ (boolean) Returns true if the Element has the class, otherwise false.
<div id="myElement" class="testClass"></div>
$('myElement').hasClass('testClass'); //returns true
Adds the passed in class to the Element, if the Element doesnt already have it.
myElement.addClass(className);
1. className - (string) The class name to add.
§ (element) This Element.
<div id="myElement" class="testClass"></div>
$('myElement').addClass('newClass');
<div id="myElement" class="testClass newClass"></div>
Works like Element:addClass, but removes the class from the Element.
myElement.removeClass(className);
1. className - (string) The class name to remove.
§ (element) This Element.
<div id="myElement" class="testClass newClass"></div>
$('myElement').removeClass('newClass');
<div id="myElement" class="testClass"></div>
Adds or removes the passed in class name to the Element, depending on whether or not it's already present.
myElement.toggleClass(className);
1. className - (string) The class to add or remove.
§ (element) This Element.
<div id="myElement" class="myClass"></div>
$('myElement').toggleClass('myClass');
<div id="myElement" class=""></div>
$('myElement').toggleClass('myClass');
<div id="myElement" class="myClass"></div>
Returns the previousSibling of the Element (excluding text nodes).
var previousSibling = myElement.getPrevious([match]);
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.
§ (mixed) The previous sibling Element or null if none found.
Like Element:getPrevious, but returns a collection of all the matched previousSiblings.
As Element:getPrevious, but tries to find the nextSibling (excluding text nodes).
var nextSibling = myElement.getNext([match]);
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.
§ (mixed) The next sibling Element or null if none found.
Like Element.getNext, but returns a collection of all the matched nextSiblings.
Works as Element:getPrevious, but tries to find the firstChild (excluding text nodes).
var firstElement = myElement.getFirst([match]);
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.
§ (mixed) The first sibling Element or null if none found.
Works as Element:getPrevious, but tries to find the lastChild.
var lastElement = myElement.getLast([match]);
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.
§ (mixed) The first sibling Element, or returns null if none found.
Works as Element:getPrevious, but tries to find the parentNode.
var parent = myElement.getParent([match]);
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.
§ (mixed) The target Element's parent or null if no matching parent is found.
Like Element:getParent, but returns a collection of all the matched parentNodes up the tree.
Returns all the Element's children (excluding text nodes). Returns as Elements.
var children = myElement.getChildren([match]);
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.
§ (array) A Elements array with all of the Element's children, except the text nodes.
Checks all descendants of this Element for a match.
var result = myElement.hasChild(el);
1. el - (mixed) Can be an Element reference or string id.
§ (boolean) Returns true if the passed in Element is a child of the Element, otherwise false.
<div id="Darth_Vader">
<div id="Luke"></div>
</div>
if ($('Darth_Vader').hasChild('Luke')) alert('Luke, I am your father.'); // tan tan tannn...
Empties an Element of all its children.
myElement.empty();
§ (element) This Element.
<div id="myElement">
<p></p>
<span></span>
</div>
$('myElement').empty();
<div id="myElement"></div>
Empties an Element of all its children, removes and garbages the Element. Useful to clear memory before the pageUnload.
myElement.destroy();
§ (null)
Reads the child inputs of the Element and generates a query string based on their values.
var query = myElement.toQueryString();
§ (string) A string representation of a all the input Elements' names and values.
<form id="myForm" action="submit.php">
<input name="email" value="[email protected]" />
<input name="zipCode" value="90210" />
</form>
$('myForm').toQueryString(); //Returns "[email protected]&zipCode=90210".
Returns the selected options of a select element.
var selected = mySelect.getSelected();
§ (array) An array of the selected elements.
<select id="country-select" name="country">
<option value="US">United States</option
<option value ="IT">Italy</option>
</select>
$('country-select').getSelected(); //Returns whatever the user selected.
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.
Returns a single element attribute.
var myProp = myElement.getProperty(property);
§ property - (string) The property to be retrieved.
§ (string) A string containing the Element's requested property.
<img id="myImage" src="mootools.png" title="MooTools, the compact JavaScript framework" alt="" />
var imgProps = $('myImage').getProperty('src'); //Returns: 'mootools.png'.
Gets multiple element attributes.
var myProps = myElement.getProperties(properties);
§ properties - (strings) Any number of properties to be retrieved.
§ (object) An object containing all of the Element's requested properties.
<img id="myImage" src="mootools.png" title="MooTools, the compact JavaScript framework" alt="" />
var imgProps = $('myImage').getProperties('id', 'src', 'title', 'alt');
//Returns: { id: 'myImage', src: 'mootools.png', title: 'MooTools, the compact JavaScript framework', alt: '' }
Sets an attribute or special property for this Element.
1. property - (string) The property to assign the value passed in.
2. value - (mixed) The value to assign to the property passed in.
§ (element) - This Element.
<img id="myImage" />
$('myImage').setProperty('src', 'mootools.png');
<img id="myImage" src="mootools.png" />
§ 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.
Sets numerous attributes for the Element.
1. properties - (object) An object with key/value pairs.
§ (element) This Element.
<img id="myImage" />
$('myImage').setProperties({
src: 'whatever.gif',
alt: 'whatever dude'
});
<img id="myImage" src="whatever.gif" alt="whatever dude" />
Removes an attribute from the Element.
myElement.removeProperty(property);
1. property - (string) The attribute to remove.
§ (element) This Element.
<a id="myAnchor" href="#" onmousedown="alert('click');"></a>
//Eww... inline JavaScript is bad! Let's get rid of it.
$('myAnchor').removeProperty('onmousedown');
<a id="myAnchor" href="#"></a>
Removes numerous attributes from the Element.
myElement.removeProperties(properties);
1. properties - (strings) The attributes to remove, separated by comma.
§ (element) This Element.
<a id="myAnchor" href="#" title="hello world"></a>
$('myAnchor').removeProperties('id', 'href', 'title');
<a></a>
Stores an item in the Elements Storage, linked to this Element.
myElement.store(key, value);
1. key - (string) The key you want to assign to the stored value.
2. value - (mixed) Any value you want to store.
§ (element) This Element.
$('element').store('someProperty', someValue);
Retrieves a value from the Elements storage.
myElement.retrieve(key[, default]);
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.
§ (mixed) The value linked to the key.
$('element').retrieve('someProperty'); // returns someValue (see example above)
This Hash contains the functions that respond to the first argument passed in Element:get,Element:set and Element:erase.
Element.Properties.disabled = {
get: function(){
return this.disabled;
}
set: function(value){
this.disabled = !!value;
this.setAttribute('disabled', !!value);
}
};
//Gets the "disabled" property.
$(element).get('disabled');
//Sets the "disabled" property to true, along with the attribute.
$(element).set('disabled', true);
Automatically returns the element for setters.
Additionally, you can access these custom getters and setters using an object as the parameter for the set method.
//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});
Sets the innerHTML of the Element.
myElement.set('html', [htmlString[, htmlString2[, htmlString3[, ..]]]);
1. Any number of string parameters with HTML.
§ (element) This Element.
<div id="myElement"></div>
$('myElement').set('html', '<div></div>', '<p></p>');
<div id="myElement">
<div></div>
<p></p>
</div>
Returns the inner HTML of the Element.
myElement.get('html');
§ (text) This Element's innerHTML.
Sets the inner text of the Element.
myElement.set('text', text);
1. text - (string) The new text content for the Element.
§ (element) This Element.
<div id="myElement"></div>
$('myElement').set('text', 'some text');
//The text of myElement is now 'some text'.
<div id="myElement">some text</div>
Gets the inner text of the Element.
var myText = myElement.get('text');
§ (string) The text of the Element.
<div id="myElement">my text</div>
var myText = $('myElement').get('text'); //myText = 'my text'.
Returns the tag name of the Element in lower case.
var myTag = myElement.get('tag');
§ (string) The tag name in lower case.
<img id="myImage" />
var myTag = $('myImage').get('tag'); // myTag = 'img'.
Custom Native to create and easily work with IFrames.
Creates an IFrame HTML Element and extends its window and document with MooTools.
var myIFrame = new IFrame([el][, props]);
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.
§ (element) A new IFrame HTML Element.
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.');
}
}
});
§ 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.
The Elements class allows Element methods to work on an Elements array, as well as ArrayMethods.
var myElements = new Elements(elements[, options]);
1. elements - (mixed) An array of elements or an HTMLCollection Object.
§ (array) An extended array with the Element, Elements and Array methods.
$$('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');
var myElements = new Elements(['myElementID', $('myElement'), 'myElementID2', document.getElementById('myElementID3')]);
§ 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.
§ $$, $, Element, Elements, Array
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.
var filteredElements = elements.filter(selector);
1. selector - (mixed) A single CSS selector.
§ (array) A subset of this Elements instance.
§ 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.
§ Internet Explorer fires element events in random order if they are not fired by Element:fireEvent.
Attaches an event listener to a DOM element.
myElement.addEvent(type, fn);
1. type - (string) The event name to monitor ('click', 'load', etc) without the prefix 'on'.
2. fn - (function) The function to execute.
§ (element) This Element.
<div id="myElement">Click me.</div>
$('myElement').addEvent('click', function(){
alert('clicked!');
});
§ You can stop the Event by returning false in the listener or calling Event:stop.
§ This method is also attached to Document and Window.
§ w3schools Event Attributes
Works as Element.addEvent, but instead removes the specified event listener.
myElement.removeEvent(type, fn);
1. type - (string) The event name.
2. fn - (function) The function to remove.
§ (element) This Element.
var destroy = function(){ alert('Boom: ' + this.id); } // this refers to the Element.
$('myElement').addEvent('click', destroy);
// later
$('myElement').removeEvent('click', destroy);
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.
§ 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.
The same as Element:addEvent, but accepts an object to add multiple events at once.
myElement.addEvents(events);
1. events - (object) An object with key/value representing: key the event name, and value the function that is called when the Event occurs.
§ (element) This Element.
$('myElement').addEvents({
'mouseover': function(){
alert('mouseover');
},
'click': function(){
alert('click');
}
});
§ This method is also attached to Document and Window.
§ Element:addEvent
Removes all events of a certain type from an Element. If no argument is passed, removes all events of all types.
myElements.removeEvents([events]);
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.
§ (element) This Element.
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.
§ This method is also attached to Document and Window.
§ Element:removeEvent
Executes all events of the specified type present in the Element.
myElement.fireEvent(type[, args[, delay]]);
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.
§ (element) This Element.
// Fires all the added 'click' events and passes the Element 'anElement' after one second.
$('myElement').fireEvent('click', $('anElement'), 1000);
§ This will not fire the DOM Event (this concerns all inline events ie. onmousedown="..").
§ This method is also attached to Document and Window.
Clones all events from an Element to this Element.
myElement.cloneEvents(from[, type]);
1. from - (element) Copy all events from this Element.
2. type - (string, optional) Copies only events of this type. If null, copies all events.
§ (element) This Element.
var myElement = $('myElement');
var myClone = myElement.clone().cloneEvents(myElement); //clones the element and its events
§ This method is also attached to Document and Window.
You can add additional custom events by adding properties (objects) to the Element.Events Hash
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.
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');
});
§ 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.
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).
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).
$('myElement').addEvent('mouseenter', myFunction);
§ Element:addEvent
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).
$('myElement').addEvent('mouseleave', myFunction);
§ Element:addEvent
This event fires when the mouse wheel is rotated;
$('myElement').addEvent('mousewheel', myFunction);
§ This custom event just redirects DOMMouseScroll (Mozilla) to mousewheel (Opera, Internet Explorer), making it work across browsers.
§ Element:addEvent
Custom Native to allow all of its methods to be used with any DOM element via the dollar function $.
Sets a CSS property to the Element.
myElement.setStyle(property, value);
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'.
§ (element) This element.
//Both lines have the same effect.
$('myElement').setStyle('width', '300px'); //The width is now 300px.
$('myElement').setStyle('width', 300); //The width is now 300px.
§ All number values will automatically be rounded to the nearest whole number.
Returns the style of the Element given the property passed in.
var style = myElement.getStyle(property);
1. property - (string) The css style property you want to retrieve.
§ (string) The style value.
$('myElement').getStyle('width'); //Returns "300px".
$('myElement').getStyle('width').toInt(); //Returns 300.
Applies a collection of styles to the Element.
myElement.setStyles(styles);
1. styles - (object) An object of property/value pairs for all the styles to apply.
§ (element) This element.
$('myElement').setStyles({
border: '1px solid #000',
width: 300,
height: 400
});
§ Element:getStyle
Returns an object of styles of the Element for each argument passed in.
var styles = myElement.getStyles(property[, property2[, property3[, ...]]]);
1. properties - (strings) Any number of style properties.
§ (object) An key/value object with the CSS styles as computed by the browser.
$('myElement').getStyles('width', 'height', 'padding');
//returns {width: "10px", height: "10px", padding: "10px 0px 10px 0px"}
§ Element:getStyle
Custom Native to allow all of its methods to be used with any DOM element via the dollar function $.
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.
§ Element positioning based on the qooxdoo code and smart browser fixes, LGPL License.
§ Viewport dimensions based on YUI code, BSD License.
Scrolls the element to the specified coordinated (if the element has an overflow). The following method is also available on the Window object.
myElement.scrollTo(x, y);
1. x - (number) The x coordinate.
2. y - (number) The y coordinate.
$('myElement').scrollTo(0, 100);
§ MDC Element:scrollLeft, MDC Element:scrollTop
Returns the height and width of the Element, taking into account borders and padding. The following method is also available on the Window object.
myElement.getSize();
§ (object) An object containing the width (as x) and the height (as y) of the target Element.
var size = myElement.getSize();
alert("The element is "+size.x+" pixels wide and "+size.y+"pixels high.");
Returns an Object representing the size of the target Element, including scrollable area. The following method is also available on the Window object.
myElement.getScrollSize();
§ (object) An object containing the x and y dimensions of the target Element.
var scroll = $('myElement').getScrollSize();
alert('My element can scroll to ' + scroll.y + 'px'); //alerts 'My element can scroll down to 820px'
§ MDC Element:scrollLeft, MDC Element:scrollTop, MDC Element:offsetWidth, MDC Element:offsetHeight, MDC Element:scrollWidth, MDC Element:scrollHeight
Returns an Object representing how far the target Element is scrolled in either direction. The following method is also available on the Window object.
myElement.getScroll();
§ (object) An object containing the x and y dimensions of the target Element's scroll.
var scroll = $('myElement').getScroll();
alert('My element is scrolled down ' + scroll.y + 'px'); //alerts 'My element is scrolled down to 620px'
Returns the real offsets of the element.
myElement.getPosition(relative);
relative - (Element, defaults to the document) If set, the position will be relative to this Element.
§ (object) An object with the x and y coordinates of the Element's position.
$('element').getPosition(); //returns {x: 100, y: 500};
§ QuirksMode: Find position
Returns an object with width, height, left, right, top, and bottom coordinate values of the Element.
myElement.getCoordinates(relative);
relative - (element, optional) if set, the position will be relative to this element, otherwise relative to the document.
§ (object) An object containing the Element's current: top, left, width, height, right, and bottom.
var myValues = $('myElement').getCoordinates();
{
top: 50,
left: 100,
width: 200,
height: 300,
right: 300,
bottom: 350
}
Element:getPosition
Custom class to allow all of its methods to be used with any Selectors element via the dollar function $.
Gets all the elements within an element that match the given selector.
var myElements = myElement.getElements(selector);
1. selector - (string) The CSS Selector to match.
§ (array) An Element collection.
//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 = '[email protected]';
},
'mouseleave': function(){
this.href = '#';
}
});
§ Supports these operators in attribute selectors:
§ '=' : is equal to
§ '^=' : starts-with
§ '$=' : ends-with
§ '!=' : is not equal to
Same as Element:getElements, but returns only the first.
var anElement = myElement.getElement(selector);
1. selector - (string) The CSS Selector to match.
§ (mixed) An extended Element, or null if not found.
var found = $('myElement').getElement('.findMe').setStyle('color', '#f00');
Some default Pseudo Selectors for Selectors.
§ W3C Pseudo Classes
Matches all Elements that are enabled.
':enabled'
$$('*:enabled')
$('myElement').getElements(':enabled');
Matches all elements which are empty.
':empty'
$$('div:empty');
Matches all the Elements which contains the text.
':contains(text)'
2. text - (string) The text that the Element should contain.
$$('p:contains("find me")');
Matches every nth child.
Nth Expression:
':nth-child(nExpression)'
§ nExpression - (string) A nth expression for the "every" nth-child.
$$('#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)'
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.
Matches every even child.
':even'
$$('td:even');
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.
Matches every odd child.
':odd'
$$('td:odd');
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.
Matches the first child.
':first-child'
$$('td:first-child');
Matches the last child.
':last-child'
$$('td:last-child');
Matches an only child of its parent Element.
':only-child'
$$('td:only-child');
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.
window.addEvent('domready', function() {
alert("The DOM is ready.");
});
Element.Event
JSON parser and encoder.
§ JavaScript Object Notation (JSON.org)
Converts an object or array to a JSON string.
var myJSON = JSON.encode(obj);
1. obj - (object) The object to convert to string.
§ (string) A JSON string.
var fruitsJSON = JSON.encode({apple: 'red', lemon: 'yellow'}); // returns: '{"apple":"red","lemon":"yellow"}'
Converts a JSON string into an JavaScript object.
var object = JSON.decode(string[, secure]);
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.
§ (object) The object represented by the JSON string.
var myObject = JSON.decode('{"apple":"red","lemon":"yellow"}'); //returns: {apple: 'red', lemon: 'yellow'}
§ JSON test regexp is by Douglas Crockford and Tobie Langel.
Sets and accesses cookies.
§ Based on the functions by Peter-Paul Koch QuirksMode.
§ 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.
§ In order to share the Cookie with pages located in a different path, the Cookie.options.domain value must be set.
Writes a cookie in the browser.
var myCookie = Cookie.write(key, value[, options]);
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.
§ (object) An object with the options, the key and the value. You can give it as first parameter to Cookie.remove.
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});
Reads the value of a Cookie.
var myCookie = Cookie.read(name);
2. name - (string) The name of the Cookie to retrieve.
§ (mixed) The cookie string value, or null if not found.
Cookie.read("username");
Removes a cookie from the browser.
var oldCookie = Cookie.dispose(cookie[, options]);
3. name - (string) The name of the cookie to remove or a previously saved Cookie instance.
4. options - (object, optional) See Cookie.
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); }
Creates and returns a Flash object using supplied parameters.
Flash detection and Internet Explorer/Flash Player 9 fix adapted from SWFObject.
var mySwiff = new Swiff(path[, options]);
1. path - (string) The path to the SWF file.
2. options - (object, optional) See Options below.
§ 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.
§ (element) A new HTML object Element.
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
}
});
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.
Calls an ActionScript function from JavaScript.
var result = Swiff.remote(obj, fn);
1. obj - (element) A Swiff instance (an HTML object Element).
2. fn - (string) The name of the function to execute in the Flash movie.
§ (mixed) The ActionScript function's result.
var obj = new Swiff('myMovie.swf');
//Alerts "This is from the .swf file!".
alert(Swiff.remote(obj, 'myFlashFn'));
The SWF file must be compiled with the ExternalInterface component. See the Adobe documentation on External Interface for more information.
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.
2. Chain, Events, Options
var myFx = new Fx([options]);
§ options - (object, optional) An object with options for the effect. See below.
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'
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.
§ 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.
5. Fx.Tween, Fx.Morph.
The start method is used to begin a transition. Fires the 'start' event.
myFx.start(from[, to]);
§ 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.
2. (object) - This Fx instance.
§ See examples in the documentation for each Fx subclass.
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.
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.
myFx.set(value);
§ value - (mixed) The value to immediately apply to the transition.
2. (object) - This Fx instance.
§ See examples in the documentation for each Fx subclass.
The cancel method is used to cancel a running transition. Fires the 'cancel' event.
myFx.cancel();
4. (object) - This Fx instance.
Temporarily pause a currently running effect.
myFx.pause();
4. (object) - This Fx instance.
§ 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.
Resume a previously paused effect.
myFx.resume();
§ (object) - This Fx instance.
3. The effect will only be resumed if it has been previously paused. Otherwise, the call to resume will be ignored.
CSS parsing class for effects. Required by Fx.Tween, Fx.Morph, Fx.Elements.
Has no public methods.
Contains Fx.Tween and the Element shortcut Element.tween.
Fx
The Tween effect, used to transition any CSS property from one value to another.
var myFx = new Fx.Tween(element, [, options]);
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:
§ 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.
§ 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.
§ Fx
Sets the Element's CSS property to the specified value immediately.
myFx.set(property, value);
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.
§ (object) This Fx.Tween instance.
var myFx = new Fx.Tween(element);
//Immediately sets the background color of the element to red:
myFx.set('background-color', '#f00');
If you use the property option, you must not use the property argument in the start and set methods.
Transitions the Element's CSS property to the specified value.
myFx.start([property,] [from,] to);
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.
§ (object) This Fx.Tween instance.
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');
§ 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.
see Element.Properties
Sets and gets default options for the Fx.Tween instance of an Element.
el.set('tween'[, options]);
§ options - (object) the Fx.Tween options.
§ (element) This Element.
el.set('tween', {duration: 'long'});
el.tween('color', '#f00');
el.get('tween', [options]);
1. property - (string) the Fx.Tween property argument.
2. options - (object) the Fx.Tween options.
§ (object) The Element's internal Fx.Tween instance.
el.get('tween', {property: 'opacity', duration: 'long'}).start(0);
§ 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).
Custom Native to allow all of its methods to be used with any DOM element via the dollar function $.
Element shortcut method which immediately transitions any single CSS property of an Element from one value to another.
myElement.tween(property, startvalue[, endvalue]);
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.
§ (element) This Element.
//Transitions the width of "myElement" from its current width to 100px:
$('myElement').tween('width', '100');
//Transitions the height of "myElement" from 20px to 200px:
$('myElement').tween('height', [20, 200]);
//Transitions the border of "myElement" from its current to "6px solid blue":
$('myElement').tween('border', '6px solid #36f');
§ Fx.Tween
Element shortcut method for tween with opacity. Useful for fading an Element in and out or to a certain opacity level.
myElement.fade([how]);
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.
§ This Element.
$('myElement').fade('out'); //Fades "myElement" out.
$('myElement').fade(0.7); //Fades "myElement" to 70% opacity.
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.
myElement.highlight([start, end]);
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.
If no background color is set on the Element, or its background color is set to 'transparent', the default end value will be white.
§ (element) This Element.
//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');
Allows for the animation of multiple CSS properties at once, even by a CSS selector. Inherits methods, properties, options and events from Fx.
§ Fx
var myFx = new Fx.Morph(element[, options]);
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.
§ (object) A new Fx.Morph instance.
Multiple styles with start and end values using an object:
var myEffect = new Fx.Morph('myElement', {duration: 'long', transition: Fx.Transitions.Sine.easeOut});
myEffect.start({
'height': [10, 100], //Morphs the 'height' style from 10px to 100px.
'width': [900, 300] //Morphs the 'width' style from 900px to 300px.
});
Multiple styles with the start value omitted will default to the current Element's value:
var myEffect = new Fx.Morph('myElement', {duration: 'short', transition: Fx.Transitions.Sine.easeOut});
myEffect.start({
'height': 100, //Morphs the height from the current to 100px.
'width': 300 //Morphs the width from the current to 300px.
});
Morphing one Element to match the CSS values within a CSS class:
var myEffect = new Fx.Morph('myElement', {duration: 1000, transition: Fx.Transitions.Sine.easeOut});
//The styles of myClassName will be applied to the target Element.
myEffect.start('.myClassName');
§ Fx
Sets the Element's CSS properties to the specified values immediately.
myFx.set(to);
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.
§ (object) This Fx.Morph instance.
var myFx = new Fx.Morph('myElement').set({
'height': 200,
'width': 200,
'background-color': '#f00',
'opacity': 0
});
var myFx = new Fx.Morph('myElement').set('.myClass');
Executes a transition for any number of CSS properties in tandem.
myFx.start(properties);
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.
§ (object) This Fx.Morph instance.
var myEffects = new Fx.Morph('myElement', {duration: 1000, transition: Fx.Transitions.Sine.easeOut});
myEffects.start({
'height': [10, 100],
'width': [900, 300],
'opacity': 0,
'background-color': '#00f'
});
§ 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.
see Element.Properties
Sets a default Fx.Morph instance for an Element.
el.set('morph'[, options]);
1. options - (object, optional) The Fx.Morph options.
§ (element) This Element.
el.set('morph', {duration: 'long', transition: 'bounce:out'});
el.morph({height: 100, width: 100});
Gets the default Fx.Morph instance for the Element.
el.get('morph');
1. options - (object, optional) The Fx.Morph options. If these are passed in, a new instance will be generated.
§ (object) The Fx.Morph instance.
el.set('morph', {duration: 'long', transition: 'bounce:out'});
el.morph({height: 100, width: 100});
el.get('morph'); //The Fx.Morph instance.
Animates an Element given the properties passed in.
myElement.morph(properties);
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.
§ (element) This Element.
With an object:
$('myElement').morph({height: 100, width: 200});
With a selector:
$('myElement').morph('.class1');
§ Fx.Morph
Fx.Transitions overrides the base Fx constructor, and adds the possibility to use the transition option as string.
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
A collection of tweening transitions for use with the Fx classes.
//Elastic.easeOut with default values:
var myFx = $('myElement').effect('margin', {transition: Fx.Transitions.Elastic.easeOut});
§ Robert Penner's Easing Equations
Displays a linear transition.
Displays a quadratic transition. Must be used as Quad.easeIn or Quad.easeOut or Quad.easeInOut.
Displays a cubicular transition. Must be used as Cubic.easeIn or Cubic.easeOut or Cubic.easeInOut.
Displays a quartetic transition. Must be used as Quart.easeIn or Quart.easeOut or Quart.easeInOut.
Displays a quintic transition. Must be used as Quint.easeIn or Quint.easeOut or Quint.easeInOut
Used to generate Quad, Cubic, Quart and Quint.
§ The default is p^6.
Displays a exponential transition. Must be used as Expo.easeIn or Expo.easeOut or Expo.easeInOut.
Displays a circular transition. Must be used as Circ.easeIn or Circ.easeOut or Circ.easeInOut.
Displays a sineousidal transition. Must be used as Sine.easeIn or Sine.easeOut or Sine.easeInOut.
Makes the transition go back, then all forth. Must be used as Back.easeIn or Back.easeOut or Back.easeInOut.
Makes the transition bouncy. Must be used as Bounce.easeIn or Bounce.easeOut or Bounce.easeInOut.
Elastic curve. Must be used as Elastic.easeIn or Elastic.easeOut or Elastic.easeInOut
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.
var myTransition = new Fx.Transition(transition[, params]);
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.
§ (function) A function with easing functions.
//Elastic.easeOut with user-defined value for elasticity.
var myTransition = new Fx.Transition(Fx.Transitions.Elastic, 3);
var myFx = $('myElement').effect('margin', {transition: myTransition.easeOut});
§ Fx.Transitions
An XMLHttpRequest Wrapper.
Chain, Events, Options
var myRequest = new Request([options]);
1. options - (object, optional) See below.
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="[email protected]">
<input name="zipCode" value="90210">
</p>
</form>
JavaScript
$('myForm').send();
Note:
The URL is taken from the action attribute of the form.
Request Specifically made for receiving HTML.
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
Wrapped Request with automated sending and receiving of JavaScript Objects in JSON Format.
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
The slide effect slides an Element in horizontally or vertically. The contents will fold inside.
§ Fx.Slide requires the page to be in Standards Mode.
§ Fx
var myFx = new Fx.Slide(element[, options]);
1. elements - (element) The element to slide.
2. options - (object, optional) All of Fx options in addition to mode and wrapper.
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.
1. open - (boolean) Indicates whether the slide element is visible.
//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.
});
§ 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.
Slides the Element in view horizontally or vertically.
myFx.slideIn([mode]);
1. mode - (string, optional) Override the passed in Fx.Slide option with 'horizontal' or 'vertical'.
§ (object) This Fx.Slide instance.
var myFx = new Fx.Slide('myElement').slideOut().chain(function(){
this.show().slideIn('horizontal');
});
Slides the Element out of view horizontally or vertically.
myFx.slideOut([mode]);
1. mode - (string, optional) Override the passed in Fx.Slide option with 'horizontal' or 'vertical'.
§ (object) This Fx.Slide instance.
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');
Slides the Element in or out, depending on its state.
myFx.toggle([mode]);
1. mode - (string, optional) Override the passed in Fx.Slide option with 'horizontal' or 'vertical'.
§ (object) This Fx.Slide instance.
var myFx = new Fx.Slide('myElement', {
duration: 1000,
transition: Fx.Transitions.Pow.easeOut
});
//Toggles between slideIn and slideOut twice:
myFx.toggle().chain(myFx.toggle);
Hides the Element without a transition.
myFx.hide([mode]);
1. mode - (string, optional) Override the passed in Fx.Slide option with 'horizontal' or 'vertical'.
§ (object) This Fx.Slide instance.
var myFx = new Fx.Slide('myElement', {
duration: 'long',
transition: Fx.Transitions.Bounce.easeOut
});
//Automatically hides and then slies in "myElement":
myFx.hide().slideIn();
Shows the Element without a transition.
myFx.show([mode]);
1. mode - (string, optional) Override the passed in Fx.Slide option with 'horizontal' or 'vertical'.
§ (object) This Fx.Slide instance.
var myFx = new Fx.Slide('myElement', {
duration: 1000,
transition: Fx.Transitions.Bounce.easeOut
});
//Slides "myElement" out.
myFx.slideOut().chain(function(){
//Waits one second, then the Element appears without transition.
this.show.delay(1000, this);
});
See Element.Properties.
Sets a default Fx.Slide instance for an element. Gets the previously setted Fx.Slide instance or a new one with default options.
el.set('slide'[, options]);
1. options - (object) the Fx.Morph options.
§ (element) this element
el.set('slide', {duration: 'long', transition: 'bounce:out'});
el.slide('in');
el.get('slide');
1. options - (object, optional) the Fx.Slide options. if passed in will generate a new instance.
§ (object) the Fx.Slide instance
el.set('slide', {duration: 'long', transition: 'bounce:out'});
el.slide('in');
el.get('slide'); //the Fx.Slide instance
Custom Native to allow all of its methods to be used with any DOM element via the dollar function $.
Slides this Element in view.
myElement.slide(how);
1. how - (string, optional) Can be 'in', 'out', 'toggle', 'show' and 'hide'. Defaults to 'toggle'.
§ (element) this Element.
$('myElement').slide('hide').slide('in');
Scrolls any element with an overflow, including the window element.
§ Fx.Scroll requires the page to be in Standards Mode.
§ Fx
var myFx = new Fx.Scroll(element[, options]);
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.
§ (object) A new Fx.Scroll instance.
var myFx = new Fx.Scroll('myElement', {
offset: {
'x': 0,
'y': 100
}
}).toTop();
§ 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.
Scrolls the specified Element to the x/y coordinates immediately.
myFx.set(x, y);
1. x - (integer) The x coordinate to scroll the Element to.
2. y - (integer) The y coordinate to scroll the Element to.
§ (object) This Fx.Scroll instance.
var myElement = $(document.body);
var myFx = new Fx.Scroll(myElement).set(0, 0.5 * document.body.offsetHeight);
Scrolls the specified Element to the x/y coordinates provided.
myFx.start(x, y);
1. x - (integer) The x coordinate to scroll the Element to.
2. y - (integer) The y coordinate to scroll the Element to.
§ (object) This Fx.Scroll instance.
var myElement = $(document.body);
var myFx = new Fx.Scroll(myElement).start(0, 0.5 * document.body.offsetHeight);
§ Scrolling to negative coordinates is impossible.
Scrolls the specified Element to its maximum top.
myFx.toTop();
§ (object) This Fx.Scroll instance.
//Scrolls "myElement" 200 pixels down from its top and, after 1.5 seconds,
//back to the top.
var myFx = new Fx.Scroll('myElement', {
onComplete: function(){
this.toTop.delay(1500, this);
}
}).scrollTo(0, 200).chain(function(){
this.scrollTo(200, 0);
});
Scrolls the specified Element to its maximum bottom.
myFx.toBottom();
§ (object) This Fx.Scroll instance.
//Scrolls the window to the bottom and, after one second, to the top.
var myFx = new Fx.Scroll(window).toBottom().chain(function(){
this.toTop.delay(1000, this);
});
Scrolls the specified Element to its maximum left.
myFx.toLeft();
§ (object) This Fx.Scroll instance.
//Scrolls "myElement" 200 pixels to the right and then back.
var myFx = new Fx.Scroll('myElement').scrollTo(200, 0).chain(function(){
this.toLeft();
});
Scrolls the specified Element to its maximum right.
myFx.toRight();
§ (object) This Fx.Scroll instance.
//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);
Scrolls the specified Element to the position the passed in Element is found.
myFx.toElement(el);
1. el - (mixed) A string of the Element's id or an Element reference to scroll to.
§ (object) This Fx.Scroll instance.
//Scrolls the "myElement" to the top left corner of the window.
var myFx = new Fx.Scroll(window).toElement('myElement');
§ See Element:getPosition for position difficulties.
Fx.Elements allows you to apply any number of styles transitions to a collection of Elements.
Fx
new Fx.Elements(elements[, options]);
1. elements - (array) A collection of Elements the effects will be applied to.
2. options - (object, optional) Same as Fx options.
§ (object) A new Fx.Elements instance.
var myFx = new Fx.Elements($$('.myElementClass'), {
onComplete: function(){
alert('complete');
}
}).start({
'0': {
'height': [200, 300],
'opacity': [0,1]
},
'1': {
'width': [200, 300],
'opacity': [1,0]
}
});
§ Includes colors but must be in hex format.
Applies the passed in style transitions to each object named immediately (see example).
myFx.set(to);
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.
§ (object) This Fx.Elements instance.
var myFx = new Fx.Elements($$('.myClass')).set({
'0': {
'height': 200,
'opacity': 0
},
'1': {
'width': 300,
'opacity': 1
}
});
Applies the passed in style transitions to each object named (see example).
myFx.start(obj);
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.
§ (object) This Fx.Elements instance.
var myElementsEffects = new Fx.Elements($$('a'));
myElementsEffects.start({
'0': { //let's change the first element's opacity and width
'opacity': [0,1],
'width': [100,200]
},
'4': { //and the fifth one's opacity
'opacity': [0.2, 0.5]
}
});
Enables the modification of two CSS properties of an Element based on the position of the mouse while the mouse button is down.
Events, Chain
var myDragInstance = new Drag(el[, options]);
1. el - (element) The Element to apply the transformations to.
2. options - (object, optional) The options object.
§ 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.
§ 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.
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'}
});
§ Drag requires the page to be in Standards Mode.
§ W3Schools: CSS Units
Attaches the mouse listener to the handle, causing the Element to be draggable.
myDrag.attach()