Getting Started with MooTools

This tutorial introduces one of the most popular JavaScript frameworks today, MooTools. MooTools, which stands for My Object Oriented Tools, is compatible with Internet Explorer 6+, Firefox, Opera and Chrome. MooTools is designed to be compact, modular, and of course, object oriented. MooTools is designed for intermediate to expert JavaScript programmers, so make sure you have enough experience before diving in.

Getting MooTools

Getting MooTools is fairly simple. MooTools comes in two parts, known as Core and More. Core contains the core classes and modules of the framework, while More contains the additional classes which can be included based on an application’s needs. MooTools has powerful builder pages which can customize Core and More based on our needs. The current stable version (at the time of writing this article) of MooTools Core is 1.4.5 and More is 1.4.0.1.

Element Selectors

One of the most basic operations of any JavaScript framework is the selection of elements. MooTools uses Slick as its selector engine. MooTools supports many different types of selectors. This section covers some of the most useful and important selectors.

Selecting an Element by ID

If we want to select an element by ID in plain JavaScript, we need to use the long document.getElementById('id_of_element') syntax. MooTools, like many other JavaScript frameworks, shortens this by using $ to select elements. Your code ends up looking like this:

var element =  $('id_of_element');

This will create problems if you include MooTools and other libraries that use $ (e.g. jQuery) on the same page. To overcome this situation MooTools has provided document.id() as another way to select elements. Your code to select elements by id now looks like this:

var element =  document.id('id_of_element');

Selecting Elements by Class

This will return an array of elements of a certain class. To get each individual element, we need to traverse the array, as shown below.

$$('.class_name').each(function(ele){
  console.log(ele);
});

Selecting Elements by Attribute Patterns

The following examples select elements whose id and class attributes begin with a certain pattern.

$$('[id^=id_start_]').each(function(ele){
  console.log(ele);
});

$$('[class^=class_start_]').each(function(ele){
  console.log(ele);
});

Similarly, the following examples match elements whose id and class attributes end with a certain pattern.

$$('[id$=_end_id]').each(function(ele){
  console.log(ele);
});

$$('[class$=_end_class]').each(function(ele){
  console.log(ele);
});

The DomReady Event

DomReady is an event which can only be bound to the window object. DomReady executes as soon as the DOM is loaded, which can be much earlier than the window.load event, which waits for all other resources to load. I suggest reading this in depth comparison of DomReady and window.load. The following example uses DomReady to wait until the DOM loads before querying it.

window.addEvent('domready', function(){
  if(document.id('id_of_element'))
  {
    alert('Element Exists');
  }
});

Element Creation

MooTools can create new HTML elements and inject them into the DOM. Creating a new HTML element in MooTools is very simple. For example, the following code creates a new div element.

var new_div = new Element('div', {'class': 'new_div'});

The previous code creates a new element, but does not inject it into the DOM. To perform the injection, you need to call the adopt() method. The following example shows how this is done.

var new_div = new Element('div', {'class': 'new_div'});

$$('body').adopt(new_div);

When this code gets executed, you can see the new div added just before the closing body tag.

Event Binding

Event binding causes code to be executed when certain events are performed on an element. Click, double click, and hovering are examples of common events. You can also create your own custom events, but that is beyond the scope of this article. As an example of MooTools event binding, the following code adds a simple click event handler to an element.

document.id('id_of_ele').addEvent('click', function(){
  console.log('I was just clicked');
});

You can also add events to dynamically created elements. The following code adds a click handler to a dynamically created element.

var new_div = new Element('div', {'class': 'new_div'});
$$('body').adopt(new_div);
new_div.addEvent('click', function(){
  console.log('I was just clicked');
});

Browser Detection

Last, but not least, is browser detection with MooTools. This is required when you want to write conditional code based on the user’s browser. MooTools provides the Browser object, which gets populated on page load. The following example uses a switch statement to identify the current browser.

switch(Browser.name)
{
  case "safari":
    console.log('I am Safari');
    break;
  case "chrome":
    console.log('I am Chrome');
    break;
  case "firefox":
    console.log('I am FireFox');
    break;
  case "opera":
    console.log('I am Opera');
    break;
  case "ie":
    console.log('I am IE');
    break;
}

Conclusion

This article has covered a lot of the MooTools basics. There are some great resources out there for learning to use MooTools effectively. I have learned a lot from the MooTools Docs and The David Walsh Blog. You can also refer to my MooTools work.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Jagz W

    It seems most to selectors are same as in jquery then what is the advantages learning new mootools ? i think all this can be achieved by jquery.

    • Ahmad Alfy

      There’re differences between the two libraries … jQuery’s description of itself talks about HTML, events, animations, Ajax, and web development. MooTools talks about object oriented-ness and writing powerful and flexible code. jQuery aspires to “change the way you write JavaScript” while MooTools is designed for the intermediate to advanced JavaScript developer.

      If you think of the tasks that we want to accomplish in JavaScript strictly in terms of “get stuff on the page and do stuff to it” then jQuery is probably the best choice. It excels at offering a very expressive system for describing behavior on the page in a way that doesn’t feel like programming sometimes. You can still use the rest of JavaScript to do what you want to do, but if you’re focused on the DOM – changing CSS properties, animating things, fetching content via AJAX, etc – most of what you’ll end up writing will be covered by jQuery, and what isn’t will likely be plain-old JavaScript. jQuery does provide some methods that aren’t about the DOM; for example, it provides a mechanism for iterating over arrays – $.each(array, fn) – or, for example, it offers a trim method for strings – $.trim(str). But there aren’t a ton of these types of utility methods, which is fine because, for the most part, if you’re just getting stuff out of the DOM, iterating over them, and altering them in some way (adding html, changing styles, adding event listeners for click and mouseover, etc) you don’t need much else.

      But if you think of JavaScript’s scope in its full breadth, you can see that jQuery doesn’t focus on things outside of the DOM. This is one of the reasons it is so easy to learn, but it also limits the ways it can help you write JavaScript. It’s just not trying to be anything other than a solid programming system for the DOM. It doesn’t address inheritance nor does it address the basic utilities of all the native types in the JavaScript language, but it doesn’t need to. If you want to mess around with strings, dates, regular expressions, arrays and functions, you can. It’s just not jQuery’s job to help you do it. JavaScript as a language is there at your feet. jQuery makes the DOM your playground, but the rest of JavaScript is just not in its scope.

      This is where MooTools is vastly different. Rather than focusing exclusively on the DOM (though, as I’ll get into in a bit, it offers all the functionality that jQuery does but accomplishes this in a very different manner), MooTools takes into its scope the entire language. If jQuery makes the DOM your playground, MooTools aims to make JavaScript your playground, and this is one of the reasons why it’s harder to learn.

      • http://www.xpertdeveloper.com Avinash Zala

        Hi Ahmad,

        Thanks for such detailed explanation. Anyways I love MooTools…

  • Mildred

    This is amazing!

    • http://www.xpertdeveloper.com Avinash Zala

      glad you like this….. ;)

  • Greg Babula

    I love MooTools, wish more people used it as their go-to library

  • Richard Markette

    Yay for MooTools, been using it for years and I love it. Glad to see it getting some attention from the SitePoint family.