Additional Element Extensions

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.

Element.Dimensions.js

This file contains all the logic needed to figure out the size of things and a few helpers like .scrollTo.

Element.scrollTo

Scrolls an element to the coordinates you specify; note that this isn't a smooth transition; it just jumps to that location.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

$('scrollExample').scrollTo(0, 30); //jump 30px down
execute this code

Element.getSize

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},
//}
execute this code

Element.getPosition

Returns an object with the offsetLeft and offsetTop as x and y properties:

$('positionExample').getPosition();
//returns something like {x:20, y:570}
execute this code

Note: getPosition was previously getOffsets. See the svn revision 241

Element.getTop, .getLeft

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
execute this code
$('topAndLeftExample').getLeft() //returns an integer
execute this code

Element.getCoordinates

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
//}
execute this code

Note: getCoordinates was previously getPosition. See the svn revision 241

Element.Events.js

The Events class is a collection of functions for handling events across browsers. Here is the documentation for Event.js.

new Event

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:

shift
true if the user pressed the shift
control
true if the user pressed the control
alt
true if the user pressed the alt
meta
true if the user pressed the meta key
code
the keycode of the key pressed
page.x
the x position of the mouse, relative to the full window
page.y
the y position of the mouse, relative to the full window
client.x
the x position of the mouse, relative to the viewport
client.y
the y position of the mouse, relative to the viewport
key
the key pressed as a lowercase string. key also returns 'enter', 'up', 'down', 'left', 'right', 'space', 'backspace', 'delete', 'esc'. Handy for these special keys.
target
the event target
relatedTarget
the event related target

$('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');
});
execute this code

Event.stop, .preventDefault & .stopPropagation

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

Event.keys

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:

  • enter - 13
  • up - 38
  • down - 40
  • left - 37
  • right - 39
  • esc - 27
  • space - 32
  • backspace - 8
  • tab - 9
  • delete - 46

Element.addEvent, addEvents

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!');
});
execute this code

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

Element.removeEvent, removeEvents

You can also use Element.removeEvent to remove an event listener. .removeEvents will remove all the events on an element.

Element.fireEvent

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!'
execute this code

Element.cloneEvents

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

Custom Events

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.

Function.bindWithEvent

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;

Element.Filters.js

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.

filterByTag

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);
execute this code

filterByClass

Filter the collection by class name:

var textareas = $$('textarea');
textareas.filterByClass('execCode');
execute this code

filterById

I'm a paragraph with id "filterExample".

var pTags = $$('p');
pTags.filterById('filterExample');
execute this code

filterByAttribute

.filterByAttribute takes three arguments:

  • name - the attribute name
  • operator - optional, the attribute operator (=, !=, *=, ^=, $=, ~= )
  • value - optional, the value (only valid if operator is specified)
$$('input').filterByAttribute('value', '=', 'search');
//should return the search box if you 
//haven't changed the value of it
execute this code

Element.Form.js

These functions help you work with forms.

Element.getValue

Returns the value of a form input. Example:

$('getValueInputExample').getValue() //returns 'some value'
execute this code

$('getValueSelectExample').getValue() //returns 'value 1'
execute this code

Element.toQueryString

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
execute this code

Element.Selectors.js

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.

$E

Selects a single (i.e. the first found) Element based on the selector passed in and an optional filter element. Arguments:

  • selector - string; the css selector to match
  • filter - optional; a DOM element to limit the scope of the selector match; defaults to document.
$E('p');//the first paragraph on this page
execute this code
$E('a', 'leftCol');//the first link in the
//left column of this page
execute this code

$ES

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")
execute this code
$ES('a','leftCol') //get all the anchor tags within $('leftCol')
//can also be expressed as $('leftCol').getElements('a');
execute this code

$$

$$ 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, .getElement

Element.getElements applies a filter on the collection:

$('leftCol').getElements('p');
execute this code

The filter can be any css expression, just like $$.

Element.getElement just returns the first item found.

Element.getElementsBySelector

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');
execute this code

Element.getElementsByClassName

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');
execute this code

Element.getElementById

Targets an element with the specified id found inside the Element. Does not overwrite document.getElementById.

$('leftCol').getElementById('scrollExample');
execute this code

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

On this page:

Page index