Why you should care about MooTools
June 9th, 2011Let me start by saying that I love jQuery. Most of the time, it makes it very easy to write sane code. Sometimes, however, it just feels weird.
For example, let’s say we need to insert a link at the beginning of a div. You might write something like:
$('#myDiv').prepend('<a href="http://my.host/path" title="This is a cool link!">Click here</a>');
-or-
$('<a href="http://my.host/path" title="This is a cool link!">Click here</a>').prependTo('#myDiv');
It seems fairly straightforward, but it’s a maintenance nightmare, because you now have raw HTML buried inside of your Javascript. If it’s complicated HTML that is being dynamically constructed, it’s all too easy to introduce hard to find browser parser errors.
MooTools, on the other hand, gives you a powerful alternative with its Element class.
To create a new DOM element you literally call a constructor and pass the tag name and attributes to it. So, for example, that same link would be built with:
var myLink = new Element('a', { href: "http://my.host/path", title: "This is a cool link!", text: "Click here" });
At the price of a handful of few extra bytes, you get clear, legible code. The equivalent of .prepend() is thus:
$('#myDiv').grab(myLink, 'top');
While this might at first seem less intuitive, you can use the same method call to insert that link before or after the selected element. Sure, you could do that with .before() or .after() in jQuery, but imagine if you needed to make the insertion point variable!
There are also a slew of additional benefits, like ECMAScript 5 array methods, support for multiple inheritance, and event handlers that make it easy to detect if the user is pressing Alt while right clicking.
Give MooTools a try, but before you do, I strongly urge you to read Sean McArthur’s excellent post, A Better Way to use Elements, on the difference between $() and $$(). If you come from a background of using Prototype, it will seem perfectly natural, but jQuery users can be caught by surprise.


