Mootools Short-cuts Part II
November 13th, 2007 in tutorials | 3 Comments
This article, which is a follow-up to How well do you know Mootools?, will be geared more towards Mootools syntax, using right and wrong examples within the Mootools framework, though some of these examples may apply to other libraries. Here we go.
Setting Multiple Styles/Properties/Events
Wrong
$('foo').setStyles({ "backgroundColor": '#f00', "color": '#fff' }).setProperty('href', 'new_href').setEvents({ "mouseover": doSomething, "mouseout": doSomethingElse });
Right
$('foo').set({ "styles": { "backgroundColor": '#f00', "color": '#fff' }, "properties": { "href": 'new_href' }, "events": { "mouseover": doSomething, "mouseout": doSomethingElse } });
While the first example isn’t too bad, all the chaining really isn’t necessary if you just use set(). I’d say it looks a lot nicer, too.
Creating New Elements
Wrong
new Element('a').setStyle('color', '#fff').setProperty('href', 'new_href').addEvent('click', doSomething);
new Element('a', { "href": 'new_href', "styles": { "color": '#fff'; }, "events": { "click": doSomething } });
This is similar to the previous example, except you can set all the values upon the creation of the element. Note that properties don’t have to be contained in a properties object.
Ajax Forms
Wrong
new Ajax('my_action.php', { "data": $('my_form').toQueryString() });
Right
$('my_form').send();
That’s a pretty nice short-cut I’d say. It’ll read the form’s properties and insert them accordingly. For example, the form’s action property will be used as the url for the Ajax request.
Selecting Elements
Wrong
$('my_ul').getChildren().getFirst();
Right
$$('#my_ul li a');
Let’s say we have a navigation list and we want to get all the links in it. While the first method is pretty short, CSS selectors are shorter, and according to my tests in this case, faster.
Resetting the Class
Wrong
$('message').removeClass('error').removeClass('alert').addClass('alert');
Right
$('message').setProperty('class', 'alert');
I know this might seem obvious to some, but sometimes we get so caught up in the library’s special functions that we don’t always think of the simplest solution. It’s happened to me.
Conclusion
That’s all I can think of for now. I’ll have to scour the forum for more misuses. Feel free to post any below (wrap your code in a pre element with a lang attribute equal to “javascript”).

Hi, I'm Chris, a passionate freelance web developer. My languages of choice are PHP and JavaScript, and that's what you'll mostly find in my blog. You'll also find updates about 