The native DOM Element object gets a lot of love in Mootools. So much in fact that in Mootools 1.1 Element gets more than one file. Of paramount importance is Element.js in the Native group. This file contains all the basic functionality for the Element class, but additional functionality can be found in the /Element directory.
This file contains all the logic needed to figure out the size of things and a few helpers like .scrollTo.
Scrolls an element to the coordinates you specify; note that this isn't a smooth transition; it just jumps to that location.
$('scrollExample').scrollTo(0, 30); //jump 30px down

Returns an object with x/y definitions for size (width/height), scroll (scroll offset left/top), and scroll size (scrollheight/width).</p>
$('getSizeExample').getSize(); //returns something like: //{ // scroll: {x:0,y:0}, // scrollSize: {x=660,y=44}, // size: {x=660,y=44}, //}

Returns an object with the offsetLeft and offsetTop as x and y properties:
$('positionExample').getPosition(); //returns something like {x:20, y:570}

Note: getPosition was previously getOffsets. See the svn revision 241
This returns the offset from the top of the element and the top of the window (or left of the element and left of the window).
This paragraph is used in the example below.
$('topAndLeftExample').getTop() //returns an integer

$('topAndLeftExample').getLeft() //returns an integer

Returns an object with definitions for width, height, left and top:
$('getCoordinatesExample').getCoordinates (); //returns something like: //{ // width:660, // height:37, // left:20, // right:680, // top:13033 //}

Note: getCoordinates was previously getPosition. See the svn revision 241
The Events class is a collection of functions for handling events across browsers. Here is the documentation for Event.js.
The constructor for the Event class takes an event object as its only argument. Then you can interact with the returned instance of the Event class using these helper functions:
$('eventExample').addEvent('keydown', function(event){ event = new Event(event); /*event is now the Event class.*/ console.log(event.key); /*returns the lowercase letter pressed*/ console.log(event.shift); /*returns true if the key pressed is shift*/ if (event.key == 's' && event.control) console.log('document saved'); });

Event.stop will stop an Event from propigating and will also execute .preventDefault
Event.preventDefault will prevent the default action of the event from completing (for example, clicking a url and executing .preventDefault will still execute the onclick event(s) attached to the link, but will NOT follow the link).
Event.stopPropagation will execute the default behavior and any events (such as onclick) attached to the element but will not allow the event to bubble up through the DOM (so that if there is an event attached to document.body.onclick and the user clicks a link, the link's events will fire, but the event on the document.body will not).
Mootools defines a handful of key codes but you can add more definitions for special uses. This allows you to add event handlers for those keys:
Event.keys.whatever = 80; $(myelement).addEvent(keydown, function(event){ event = new Event(event); if (event.key == 'whatever') console.log(whatever key clicked). });
By defualt, Mootools defines the following keys:
Those of you familiar with Prototype.js's Event object will recognize the concept; it's just a different syntax. Note that the event name you give it ("click" or "mouseover") doesn't have the "on" prefix.
this paragraph is used for the examples below
$('addEventExample').addEvent('click', function() { alert('click!'); });

Why use this instead of just doing $('addEventExample').onclick = alert('click'); ? Well, using event listeners like this allows you to have more than one. If you do .onclick = myFunction() then you can only have one event watching that click. Click might not be a great example there, but certainly something like window.onload is something you might want to have numerous events monitoring.
Element.addEvents is the same only the argument is an object:
$('addEventExample').addEvents({ mouseover: function() {this.setStyle('color','#f00')}, mouseout: function() {this.setStyle('color','#000')} });

You can also use Element.removeEvent to remove an event listener. .removeEvents will remove all the events on an element.
Fires the specified event on an element. For instance, if you set up an event for clicking an element, you can execute that even if the user doesn't click it:
$('fireEventExample').addEvent('click', function(){alert('click!')}); $('fireEventExample').fireEvent('click'); //alerts 'click!'

Element.clone does not clone the events associated with that element. It's not that often that you want to do this, but if you need to, .cloneEvents will do the trick:
$(new).cloneEvents(old); //copies the events from old to new $(new).cloneEvents(old, 'click');//copies only the click events from old to new
Mootools 1.1 adds the concept of custom events. These are events that are fired when a set of conditions that you code occur. A good example of this is window.addEvent('domready'... domready is not a browser defined event; it is an event that Mootools defines.
Adding a custom event is pretty easy. Here's the custom event for "mouseenter":
Element.Events.extend({ 'mouseenter': { type: 'mouseover', map: function(event){ event = new Event(event); if (event.relatedTarget == this || this.hasChild(event.relatedTarget)) return; this.fireEvent('mouseenter', event); } } });
The "type" specifies when the event should be tested. In this case, the event defined in the "map" method is tested anytime the mouseover event occurs for the element. The function is tested to see if the relative target for the mouseover event is the current element or one of its children and, if not, it fires mouseenter.
Mootools defines, by default, 4 custom events: mouseenter, mouseleave, mousewheel, and domready.
With bindWithEvent you'll get the mootools Event wrapper as the first argument:
function fn(event){ //event is the mootools event, that supports all the cool stuff like event.page.y //position of the mouse in the page event.key //the key pressed event.shift //if shift has been pressed to trigger the event //and tons of others, refer to the docs, Native/Event.js //the keyword this is the element, because we used element in the bindWithEvent argument. }; element.onclick = fn.bindWithEvent(element);
Basically bind withEvent will do this automatically for you:
function fn(event){ event = new Event(event); }; element.onclick = fn;
The $$ function allows you to collect HTML elements using css selectors and tag names. This file provides filters that you can apply to such collections.
Filters the collection by a specified tag name. Returns a new Elements collection, while the original remains untouched.
var everything = $$('*'); var pTags = everything.filterByTag('p'); console.log(pTags);

Filter the collection by class name:
var textareas = $$('textarea'); textareas.filterByClass('execCode');

I'm a paragraph with id "filterExample".
var pTags = $$('p'); pTags.filterById('filterExample');

.filterByAttribute takes three arguments:
$$('input').filterByAttribute('value', '=', 'search'); //should return the search box if you //haven't changed the value of it

These functions help you work with forms.
Returns the value of a form input. Example:
$('getValueInputExample').getValue() //returns 'some value'

$('getValueSelectExample').getValue() //returns 'value 1'

This converts an element's child inputs to a query string. Example:
This is the html used below:
<form id="exampleForm"> <input name="name" value="bob"> <input name="likes" value="cheese"> </form>
$('exampleForm').toQueryString(); //returns name=bob&likes=cheese

These selectors let you find elements in the DOM. Note that $$ is defined in Element.js, but it only lets you get elements by tag name.
Selects a single (i.e. the first found) Element based on the selector passed in and an optional filter element. Arguments:
$E('p');//the first paragraph on this page

$E('a', 'leftCol');//the first link in the //left column of this page

Returns a collection of Elements that match the selector passed in limited to the scope of the optional filter. Element.getElements for an alternate syntax. Returns an instance of the Elements class.
$ES("a") //gets all the anchor tags; synonymous with $$("a")

$ES('a','leftCol') //get all the anchor tags within $('leftCol') //can also be expressed as $('leftCol').getElements('a');

$$ is defined in Element.js, but when you include Element.Selectors.js, it becomes much more useful; you'll use it a LOT.
With Element.Selectors.js you can pass this selector any css style selector and it will return all the matching elements. The more specific you are, the faster the selection. Note that selecting items from a very large document can be CPU intensive.
$$('div'); //all the divs on the page $$('div.myclass'); //all the divs on the page with the class 'myclass' $$('#myElement div') //all the divs in $('myElement') $$('div#myElement div') //the same, but faster because the type //of input of myElement is defined $$('div p a'); //all anchors in paragraphs in divs
You get the idea. The result should be stored if you're going to use it more than once so that the search is only performed once:
var clickers = $$('div#section a.clicker'); clickers.each(function(link) {.....}); //later something else... clickers.filter(function(link) {.....}); //etc.
Be sure to read up on $$ as it's main function is creating instances of Elements and applying the Mootools extensions in the Element class to DOM elements.
Element.getElements applies a filter on the collection:
$('leftCol').getElements('p');

The filter can be any css expression, just like $$.
Element.getElement just returns the first item found.
Same as Element.getElements, but allows for comma separated selectors, as in css. Alternate syntax for $$, where filter is the Element.
$('leftCol').getElementsBySelector('p, b, textarea.execCode');

Returns all the elements that match a specific class name. Here for compatibility purposes. can also be written: document.getElements('.className'), or $$('.className')
$('leftCol').getElementsByClassName('execCode');

Targets an element with the specified id found inside the Element. Does not overwrite document.getElementById.
$('leftCol').getElementById('scrollExample');

mootorial/03-native/00-element-extensions.txt · Last modified: 2008/06/07 05:41 by nisimjoseph