A Better Way to use Elements

Written By , on Friday, March 19th 2010, 5:41pm

Javascript development in the browser is all about the Elements. Manipulating the DOM happens every few lines of code. It’s important enough that some libraries provide little more than DOM enhancements. Not to worry though, MooTools provides greatly in this area as well.

$ and $$

Most of you probably know the two document methods getElementById and querySelectorAll; because if you do, you understand how we select elements with MooTools methods. For those of you that don’t, you provide an ID string of an element in to getElementById, and a CSS selector string to querySelectorAll. The functions $ (which is an alias to document.id, see this post on Dollar Safe Mode for details) and $$ are basically equivalent to getElementById and querySelectorAll, respectively. Of course, since it’s MooTools, they’re more than that.

The dollar function, if given a string, will basically call getElementById on the document. If passed an element, it will just return the element, and if you pass an object with a toElement method, it will try to convert it to an element (we’ll explore that more a couple sections down). A key difference you’ll find between MooTools’ dollar function and jQuery’s is this: MooTools’ $() will only ever return 1 Element, and it will return null if no matching element is found. This means unless you’re absolutely 110% certain the element will exist, you’ll need to check the returned value before starting to call Element methods on it.

    var loginEl = $('Login');
    if (loginEl) {
            loginEl.fade('in');
    }  

The MooTools Team prefers two separate methods for the selecting elements; to remove any doubt about what a certain function call may be returning, we have one method for individual elements and another for multiple elements. In this case, it’s preferable to be explicit, instead of relying to ambiguous auto-magic. When we see $, we expect an element if it exists. When we see $$, we expect an array of elements (which, as you know, an array can always be empty). The double dollar function has some neat tricks that are explained in its own section below.

All this talk about Elements, but only about how to select them. MooTools also provides an excellent Element construction API.

new Element()

With vanilla JS (mmm, vanilla…), you’d use document.createElement whenever you wanted to create and add a new element to the DOM. MooTools tries to make the JavaScript API more pleasant to use; part of that is a more consistent and easy to use syntax and part of it is using more Object-Oriented programming practices. It feels a lot more OO when creating objects using the new keyword, whereas the standard way is more procedural.

It turns out that every element you could create inherits from the Element prototype. Specifically, the elements you create through document.createElement would be HTMLDivElement, or HTMLParagraphElement, or whichever element you create. Like I said, they all inherit from the base Element prototype, and then HTMLElement, and so on. MooTools extends the base Element class, so that all elements receive some MooTools love.

MooTools augments the Element native, providing a super-duper sweet constructor. You can provide the tag name, and then an object of properties to set on the new element. The returned object is of the same type as the $ method mentioned above. The properties you can set are fairly extensive, so check out the documentation to learn more about them, but here’s a demonstration.

toElement

The dollar method provides another function: converting the instance of class into an element(-al?) form. This is similar to a toString function, which converts objects into strings when needed. You can define a method in a class called toElement, and return an element to “represent” the instance. Let’s take a look at a snippet from a Person Class:

Several extensions in MooTools More take advantage of this, like Form.Request, Form.Validator, HtmlTable, and others. And many plugins in the Forge use this approach as well. This means that after creating an instance of one of these classes, you can just hold on to the instance in your code. Whenever you want to affect the element that the instance is controlling, you just use $(instance) to retrieve it.

Aaron even cooked up a ToElement mixin, and wrote a bit more about this over here.

Elements

I pointed out earlier that $$ returns an array-like object containing Elements. It actually returns an object called exactly that: Elements. Behind the scenes, MooTools gets an array of all the elements that meet the selector (so it’s still an array), and then extends the array with all the Elements methods. Why would we want that?

All the methods that MooTools adds to the Element native are added to the Elements class as well. You can do some pretty nifty chaining because of this. First of all, you don’t have to check that it didn’t return null. This is because any method you call on Elements, will loop through the array and try to call the method on each individual element. Even with an empty array, the loop won’t cause an error. And any method you call that would normally return a value, will return an array of the values from each element. An example should make this clearer:

    //assigns a click event to all A tags
    $$('a').addEvent('click',  function(e) {
            e.preventDefault();
            alert(this.href);
    });  

    //gets all divs with an id set, and then returns
    //an array of the IDs  sorted alphabetically
    var ids = $$('div[id]').get('id').sort();  

    //gets all divs with a UL immediately inside
    //and assigns a class name to  the divs
    $$('div > ul').getParent().addClass('has-list');

While you could put together long chains acting on all the elements you’ve selected, I’d advise against this. It certainly looks cool, and will work fine one or 2 methods out on the chain. But every method call will cause another loop through all the elements. If you’re doing a lot of things to every element, you might as well do it all in a single pass. I’ll show you what I mean.

    //this would loop through each time at addEvent, addClass, and fade
    $$('li  a').addEvent('click', function(e) {}).addClass('alertable').fade('in');  

    //whereas this will only cause 1 loop
    $$('li a').each(function(link)  {
            link.addEvent('click', function(e) {
                     alert(this.title);
            });
            link.addClass('alertable');
            link.fade('in');
    }); 

Still, when doing something simple, you can skip the each call, since Elements will handle that for you.

Concluding

MooTools provides a lot of expressive power when working with the DOM. It’s consistent API makes it a snap to add events, change styles, create elements and more. The object oriented nature of its implementation makes it so that you can extend Elements for your own purposes. Look forward to my next post where I’ll talk about extending Elements in various ways and cover best practices for when you decide to bend Elements to your own will.

Sean McArthur is a software developer at Blazonco.com who is madly in love with MooTools. Most of his contributions involve sharing tips and information about MooTools (and programming in general) at his blog and on Twitter.

MooTools Roundup February 2010

Written By David Walsh, on Thursday, March 11th 2010, 9:11pm

The foundation of every great open source project is its community. The MooTools Team creates the base framework code but it’s all of you that take the framework and build outstanding plugins. These are just some of the new developments floating around the MooTools community.

12 Steps to MooTools Mastery

Jacob Thornton’s NetTuts article, 12 Steps to MooTools Master, is a high-level introduction to the MooTools JavaScript framework. The informative article touches on such MooTools topics as Mutators, Prototypal Inheritance, custom events, binding, and more. This tutorial probably isn’t for the complete beginner, but is a good place to start for people still relatively new to MooTools and those considering it for the first time.

http://net.tutsplus.com/tutorials/javascript-ajax/12-steps-to-mootools-mastery/

Meio.Autocomplete

Meio.Autocomplete

Meio.Autocomplete is the latest plugin from MooTools Contributor Fábio M. Costa. Fábio’s class is packed full of options and events, making it one of the most flexible MooTools Autocomplete plugin available. Great work Fábio!

http://mootools.net/forge/p/meio_autocomplete

DynamicTextarea

DynamicTextarea

DynamicTextarea is a MooTools class that resizes TEXTAREA elements as the user types. DynamicTextarea boasts numerous options and events for maximum control over chosen TEXTAREAs.

http://mootools.net/forge/p/dynamictextarea

Array.Math

Array.Math is an outstanding set of Math methods you can add to JavaScript’s native Array object. Need to find the sum of numbers in an array? Need to normalize elements in an array? Need to get the vector length of an array of numbers? Be sure to download Array.Math! Kudos to Arian Stolwijk for his excellent work!

http://mootools.net/forge/p/array_math

LazyLoader

LazyLoader is a unique MooTools plugin created by David Chan which allows you to defer loading of MooTools classes until they are needed. This is especially helpful when building large web applications. LazyLoader is very easy to use and implement.

http://mootools.net/forge/p/lazyloader

Locate

Locate

Locate is a Geolocation plugin authored by Christopher Beloch. Christopher’s plugin taps into the power of HTML5 and offers a few useful options and events to control the Locate instance.

http://mootools.net/forge/p/locate

Keep Up the Good Work!

These are just a few of the great MooTools plugins floating around the MooTools community recently. Keep up the good work and we look forward to featuring your plugins in future posts!

More Than Meets the Eye: Form.Request

Written By Aaron Newton, on Thursday, March 4th 2010, 5:06pm

MooTools More features a diverse, powerful collection of Classes (60 plugins!!) and some are my favorite tools that I use over and over again. I thought I’d take some time to dig into some of the plugins in MooTools More that I think are interesting and really useful that maybe you haven’t had time to really sink your teeth into (or, perhaps, you haven’t found a reason to). So I’m going to take some time to talk about some of the plugins in More each month, sharing not only how they work, but how they work together and maybe even why you’d use them. Today I’m going to talk about the Form.Request plugin.

Request and Request.HTML

MooTools Core ships with three AJAX modules, two of which include element methods (Request.JSON, the third module, doesn’t alter the Element prototype). Request.js provides the Element prototype with a send method that lets you post a form (as in, $('myFormElement').send([request options go here])), and Request.HTML.js provides the Element prototype with a load method that lets you replace the contents of any DOM element with text returned from a server request (as in $('myElement').load([request options go here])). I use these fairly often, though I probably use the Request and Request.HTML constructors just as much if not more. But in my own work I found myself needing the combination of these two things; I want to submit the form and load the response into a DOM element. Turns out, I do this all the time.

Part of writing idiomatic MooTools code is encapsulating functionality into Classes. As I’ve posted before, I do this with almost all the code that I write. The only code that I author that isn’t a class (or a static object) is a DomReady statement that instantiates classes. So when I have a pattern as clear as this - submitting a form and updating the DOM with the response - it’s time to write a class.

Form.Request

Form.Request, unlike Request.HTML, is not an extension of the Request class (that’s why it’s not Request.Form). Because it is not a Request.HTML instance, it has a reference to an instance of Request in it. Form.Request’s options include a requestOptions object that gets passed along to this instance so you can configure it however you like. By default, Form.Request derives as much as it can from the form element itself. It gets its URL from the action property and the method from the method property. The user submits the form and it cancels the submit event. Form.Request inspects that event to see if the user clicked a button and, if so, sends the name/value of that button along with the data like a regular form submission. Finally, it provides an extraData option so you an send along key/values with the form in addition to those in the inputs that the user fills out.

When the form returns a response, it handles it pretty much how Request.HTML handles any other response. It injects the HTML and evaluates any scripts in the response (this is an option, too).

And what about what we set out to do? To provide a method for Element that is the combo of load and send? The plugin provides the Element prototype with a formUpdate method that works just like those two methods combined (as in $('myForm').formUpdate({ update: $('myTarget') }), which sends the form and updates $('myTarget')).

Demo Time!

Here’s a simple demo to play with. Note how our html is plain old vanilla web 1.0 form stuff. Nothing fancy. And our JavaScript is dead simple (to get the default behavior).

Getting Fancy

Hmmm. Well, our behavior here leaves a little to be desired. The main thing that seems to be missing is any indication that something is changing - that the form has been submitted and we’re waiting for a response from the server (MooShell provides a 2 second delay on the response to simulate normal web latency). We could add an event to our instance to tell the user that something is going on, like so:

Getting Fancier

Here’s where the fact that this plugin is part of MooTools More comes into play. MooTools More includes a plugin called Spinner. I’ll talk about it in depth some other time, but in a nutshell, it puts an Ajax indicator over an element that’s being updated. It integrates with Request.HTML and Form.Request configures it for us. This happens automatically (unless you disable it in the options) and all we have to do is skin it. In this example, I’ve moved our message (that we’re sending the submission) into the Spinner options.

This magic happens without much effort for us so long as we have Spinner.js in our page. This is the default behavior. We don’t even have to specify the message text if we’re content with just the spinner image.

Even More Integration

One other thing Form.Request integrates with (also in the MooTools More library, naturally) is Form.Validator. That’s another plugin I’m not going to spend a ton of time describing in today’s post - we’ll save it for a later post as it has lots of nifty things in it. But, basically, Form.Validator (and its subclasses) provide instructions for users who are filling out a form on the fly. Form.Request integrates with it so that you don’t have to do anything to make them play nice together. Both intercept the submit event and both prevent its default behavior (i.e. sending the form), except that the Form.Validator class only stops it if the form is invalid. If Form.Request didn’t respect this privilege, it would send our form even if the Form.Validator stopped the default submission event. To get them to cooperate, all you have to do is create an instance of Form.Validator on the form. Example:

In this example, we set a minLength value for our form (50 characters). The default html in the textarea is only about 45 characters, so if you just hit submit you’ll see a red error message show up. Add some more text to our example, hit submit, and the error winks out and our form sends just as before.

Appending Results

One last trick up our sleeves here; you can append results instead of overwriting the contents of our target. Think of a to-do list kind of interface, where adding a value adds a new item to a list. To get this behavior, we just substitute Form.Request.Append into our example. There are some additional options; by default it uses another MooTools More plugin, Fx.Reveal, to smoothly transition elements into view. You can also specify if the item is appended to the top or the bottom of the container. Example:

THEND

So that pretty much covers Form.Request. I hope you find it as useful as I do. If you find it useful and fun, post a link in the comments showing off what you’ve done with it. In my next post I’ll pick another plugin (or plugins) to dig into and show off their capabilities. If there’s one you’d like to learn more about, post a suggestion for my next post in the comments.

Aaron Newton is a contributor to MooTools and the principal developer of MooTools More. He is the author of the book MooTools Essentials as well as the Mootorial online MooTools tutorial. He posts (rarely these days) at his blog Clientcide.com and (much more often) on Twitter as anutron.

MooTools at FOSDEM: Video

Written By Christoph Pojer, on Monday, February 15th 2010, 10:59am

Hello everyone,

I’m really excited and pleased to announce that my presentation “MooTools as a General Purpose Application Framework” which I delivered at the FOSDEM is now available on YouTube.

If you are not able to watch the HD-Version you can download the slides here.

Thanks again to the FOSDEM team for inviting me and for giving us such a big platform to present the MooTools project. If I could name one thing that I miss already about Brussels I would certainly say the waffles…

If you enjoyed this presentation and you want me or another developer from the MooTools Core Team to present at your conference feel free to contact us.

MooTools Roundup January 2010

Written By David Walsh, on Monday, February 15th 2010, 10:56am

The foundation of every great open source project is its community. The MooTools Team creates the base framework code but it’s all of you that take the framework and build outstanding plugins. Here are some great plugins and tutorials that have been released recently.

MooTools Driver for Rails 3 Helpers

Rails 3 has been recently been released with the new capability to create your own javascript helpers; no longer will you need to use PrototypeJS. Kevin Valdek has created a MooTools helper so that you can use your favorite javascript framework with your chosen Ruby application. Kevin mentioned that his release isn’t complete at this point so feel free to contribute! Great work Kevin!

http://kevinvaldek.com/mootools-driver-for-rails-3-helpers

Moodit

MooTools now has its own Reddit topic. Be sure to share your favorite MooTools posts with all of your friends via Reddit!

http://www.reddit.com/r/mootools/

Moodoco

Moodoco is a purely web-based client-side MooTools documentation generator with HTML5 offline capabilities created by Lim Chee Aun. It uses the GitHub API to fetch all the Markdown documentation files from the repository and stores them offline in localStorage.

http://github.com/cheeaun/moodoco

MultiSelect

MultiSelect

MultiSelect is a MooTools plugin from Blaž Maležič that turns your checkbox set into one single multi-select dropdown menu. This highly inventive plugin is a great way to make your select boxes much more appealing.

http://mootools.net/forge/p/mutiselect

Mif.Tree

Mif.Tree

Mif.Tree is a flexible tree-generation plugin that loads trees of information from javascript objects. You could, for example, output a JSON representation of a directory and view your server via HTML/javascript trees.

http://mootools.net/forge/p/mif_tree

Featured Blog: Ryan Florence

Ryan Florence’s blog has been doing an outstanding job of explaining complex MooTools concepts. Be sure to check out his blog!

http://ryanflorence.com/

Keep Up the Good Work!

These are just a few of the great MooTools plugins floating around the MooTools community recently. Keep up the good work and we look forward to featuring your plugins in future posts!