Make your MooTools Code Shorter, Faster, and Stronger

Twice a month, we revisit some of our readers’ favorite posts from throughout the history of Nettuts+. This tutorial was first published in February, 2010.

MooTools is one of the most flexible, modular, and well written JavaScript frameworks available. So many people use it but many of them don't optimize their code. This post will provide you with fifteen simple tips for making your MooTools code shorter, faster, and stronger.

1.Create Your Own MooTools Build or Pull From Google AJAX Libraries

One of the great advantages to using MooTools is that it's incredibly modular. What does that mean? Almost nothing is required unless you need it. The advantage of MooTools' modularity is that your limited, custom MooTools build can keep your JavaScript load time short.

MooTools Core Builder

Want to create a custom MooTools build for your next project? Follow these steps:

  • Go to (and/or if you'd like additional plugins)
  • Select the plugins of your choosing. Don't worry about accounting for dependencies -- the plugin builder does that for you!
  • Select the compression option of your choosing -- the YUI Compressor will provide the you with the smallest possible build of MooTools

That's it! Sometimes, however, your project requires the entire MooTools Core library. In that case, your website can save itself thousands
of requests per day by using the Google AJAX Libraries complete build of MooTools. You may do this two ways:

This first method simply includes MooTools into the page per normal. The second method allows more functionality and performance:

What's great about using the Google AJAX Libraries API is that if another website uses the AJAX Library API, that version of MooTools is already cached within their browser and the site will load faster!

2. Use jQuery and MooTools Together

While it's best to stick to one library in a given page to avoid a bunch of overhead, sometimes you can't avoid needing multiple frameworks.
Luckily MooTools can coexist with any non-prototype-based JavaScript frameworks. Here's how you can use jQuery and MooTools in the same page:

Thanks to MooTools' Dollar Safe Mode, MooTools no longer assumes the "$" method if it's already taken!

3. Save Elements and Element Collections

Developers often need to collect one element or a collection of elements. For example, you may need to grab all A elements within the page, change their color, and create tooltips from them.

The code above is grossly inefficient. Why query the DOM twice (with $$) if you can collect all of the elements once? Let's make this more efficient:

You could make this even shorter, but it's not as readable:

Readability is important, so I wouldn't recommend coding this way if you work with a team.

4. Use Element Methods on Element Collections

Cycling through an array of elements is not unique to any JavaScript framework:

What many developers aren't aware that Element collections have the same methods as Elements, so there's no need to cycle through them -- simply apply the desired functionality to the collection:

Note that the "this" keyword is used to reference the "current" element within the collection, not the collection itself.

5. Use MooTools Alias

MooTools' "alias" method allows you to rename or alias an existing method. Take the following snippet of code which is currently in the MooTools Core source:

The above code lets you call the each method instead of forEach. Using each is more readable, a quiet standard between most JavaScript frameworks, and it even saves you a few bytes in your code. If you prefer to give MooTools' Native or Class methods a custom name, feel free to!

For example, the Element Class' method for removing an Element form the DOM is:

Suppose your web app is about a given topic and you'd like to stay within that terminology for your code. Here are a few examples:

Whatever your reasons are for calling a method by a different name, just don't be afraid to do so!

6. Create Custom Pseudo Selectors

Accessing a collection of Elements in the DOM is a core responsibility of any JavaScript framework. Unfortunately it can also be taxing and the pseudo selectors you want aren't always available. Luckily MooTools allows you to easily implement your own pseudo selectors! Let's
create a pseudo selector named "disabled" that returns an element if it's disabled.

Simply add your selector to the Selectors.Pseudo object. If the new pseudo's function returns "true", the element is a match and will be returned.

Defining you own pseudo selectors is a great way to take control of your selectors!

7. Implement Methods on Existing Objects

MooTools' philosophy is that it's acceptable, even encouraged, to modify Native (String, Function, Number, etc.) prototypes when needed.
Implementing new methods on these Natives will empower them even more. Let's create a String method that will turn any string of text into
"tweet" format (add links for @reply's, links, etc.):

Now you can call "toTweet" on any string and you'll get the string back as a "tweet". Here are a few examples:

Implementing custom methods on Objects strengthens every existing and future instance of that object.

8. Extend Existing Classes

MooTools' OOP philosophy allows for a super-powerful inheritance model. Extending existing classes allows you to avoid repeating code, empower existing objects, and leverage existing functionality. MooTools Core, More, and your custom classes extend existing functionality. Consider the Request class:

Then consider Request.JSONP, which extends Request:

You see how small the Request.JSONP class is? By adding Extends: Request, the Request.JSONP class gets all of the Request Class' methods. Essentially, this small snippet of code becomes a powerhouse because it extends Request. You can even add extensions to extensions. Now consider Request.JSONP and then Scott Kyle's Request.Twitter class:

...and now Request.Twitter:

You see how a waterfall effect of extending objects can make the smallest of classes an absolute beast of a class?
Experiment with MooTools' inheritance model and don't repeat code!

9. Create Custom Events

I've already explained how flexible the MooTools selector engine is, the class system is, and how modular the framework is.1 Why would you expect anything different from MooTools' event system? Creating custom events within MooTools is as simple as it gets. Here's a basic outline of your MooTools custom event:

Here's a great example of a custom event -- listening for "alt" and "click" at the same time:

Or you can simply define a custom event so that a specific function executes any time that type of event is assigned. In my next example, any time a click event is assigned to an element, that element's cursor will be automatically changed to the "pointer" cursor.

You'll notice that if the click event is removed, the original cursor will be restored.

10. jQuery-Style Events

While the MooTools event sytax is different from jQuery's, it doesn't have to be! With a minimal amount of JavaScript you can make MooTools' event syntax reflect jQuery's.

MooTools holds all of its events in the Element.NativeElements object:

Essentially all you need to do is cycle through each element type and implement a method on the Element class, named like the event type,
that simulates what addEvent does:

Now you can listen for events like:

11. Add Events During Element Creation

If you have experience coding with MooTools, at some point you've no doubt created an element and subsequently added events to it:

There's nothing wrong with the above, per say, but you could just add those events during element creation:

12. Implement Events Within Classes

Extending classes was discussed in tip #8 above. Now let's explore the *implement* functionality within MooTools classes. What's the difference? MooTools contributor Mark Obcena says it best in his article titled Up The Moo Herd IV: There's A Class For This:

MooTools has two built-in mutators: Extends and Implements. The Extends mutator takes the class name passed on to it and makes the new class inherit directly from it, while Implements takes the class (or classes) passed and adds their methods to the new class (or mixes them in—thus mixin).

With the difference between extending and implementing, let's get back to it. Implementing events within your MooTools classes can make your classes much more flexible. Consider the following simple Overlay class:

Sure the class does what it's supposed to but it isn't nearly as flexible it could be. Now let's implement onClick, onClose, onHide, onOpen, and onShow events:

What's great about adding events to a class is that events allow your to give more options and trigger functionality when our class methods execute. In the above example, you can execute any functionality when the overlay opens, closes, shows, hides, or gets clicked.
Essentially you added two tiny snippets of code to the class:

...and the following wherever you'd like an event to be signaled...

So how can you control these events when you create an instance of the class? Add them in the options like this:

You'd be hard pressed to find a class that wouldn't benefit from implementing events!

13. Use Event Delegation

Event delegation is the process of adding an event to a parent for all of its children instead of assigning the event to each individual child. The advantage of event delegation is that you may add child elements to the parent element without needing to assign the event to that new element. If you choose to remove the event, you need only remove it from one element.

So, instead of: do this:

Don't let the ":relay()" pseudo-syntax fool you; Element.Delegation rewrites the event methods to accommodate for :relay.

14. Use Class.toElement

One hidden gem within MooTools' Class is the Class.toElement method. Class.toElement plays a small role but can help you out when it comes to accessing the primary element within a class, especially if you don't know what that element is otherwise. Implementing toElement on your class is easy:

Once you have toElement defined, you can use your class just like an element:

Look at that -- a class virtually manipulated by Element methods.

15. "return this" Within Methods For Chainability

So we've all seen how the JavaScript frameworks allow you to chain the hell out of methods. Chaining looks like this:

Holy chaining Batman! Want your classes to chain forever? No problem -- all you need to do is return "this":

Since you placed return this in each method, now you can do:

Make sure to return this wherever it makes sense. Doing so can make your Class much easier to work with and your code will be shorter!

BONUS! Use Fx Shortcuts on Elements

MooTools effects are unarguably the smoothest of any JavaScript framework. The Fx library also provides loads of control through numerous options. Let's take a look at a basic Tween which fades an element to 50%:

Did you know you didn't need to type out all of this? You could use element shortcuts like:

The above snippets, of course, rely on you wanting to use the default options. You can actually set custom options for these shortcut methods per element:

Save your self a few bytes by using Fx shortcuts!

MooTools FTW!

Hopefully I've given you some tips to improve your MooTools JavaScript code, making it shorter, faster, and stronger. Have some of your own tips to share? Place them in the comments below!



Related Articles