MooTools 1.2 Beginner's Guide

By Jacob Gube , Garrick Cheung
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. MooTools and Me

About this book

MooTools is a simple-to-use JavaScript library, ideal for people with basic JavaScript skills who want to elevate their web applications to a superior level. If you're a newcomer to MooTools looking to build dynamic, rich, and user-interactive web site applications this beginner's guide with its easy-to-follow step-by-step instructions is all you need to rapidly get to grips with MooTools.

Publication date:
December 2009
Publisher
Packt
Pages
280
ISBN
9781847194589

 

Chapter 1. MooTools and Me

In recent years, the Web has undergone a major evolution, an evolution towards highly-interactive, dynamic, responsive web pages and web applications. We're at a time where users expect (and often, demand) web interfaces that talk to them.

Gone are the days where only desktop software was associated with smooth and feature-packed user interfaces that performed complicated tasks. In fact, applications that we normally think of as traditionally being for the desktop (such as Word Processors, Image editors, and Spreadsheet software) are now moving to browser-based environments because of the many advantages of web-based applications (such as operating system/platform interdependency, interoperability with other systems, and collaborative possibilities).

JavaScript is the technology that's driving this evolution by giving web developers the capability to create complex, robust, interactive web page components and Rich Internet Applications (RIA) that respond effortlessly to user actions through a combination of techniques such as Ajax, on-the-fly DOM manipulation, and smooth, animated effects.

However, JavaScript isn't perfect (in fact, it's far from it), its syntax is sometimes unintuitive and repetitive, and often requires a great deal of code-authoring to perform complicated and cross-browser-compatible operations.

This is where MooTools steps in! By providing web developers with a set of useful and cross-browser-compatible functions, methods, and classes within an intuitive framework for writing client-side scripts, we can side-step a lot of frustration and time, typically associated with code-authoring in JavaScript:

In this chapter we shall:

  • Learn about what MooTools is

  • Discuss some advantages of using MooTools

  • Learn how to download and install MooTools

  • Learn about notable MooTools resources on the web

So let's get on with it!

What is MooTools?

MooTools (which stands for My Object-Oriented "JavaScript" Tools) is a lightweight, modular, object-oriented JavaScript framework. It greatly speeds up and enhances the development cycle of feature-rich Ajax/JavaScript web applications. Created by Valerio Proietti—who originally intended it to be an extension to the Prototype JavaScript framework—MooTools has since grown into an independent, open-source, and very robust JavaScript framework with a solid team of core developers and thousands of users who support, contribute, and rabidly evangelize the project.

MooTools, in essence, abstracts normal JavaScript code so that you can write more terse and elegant client-side scripts. It has a host of useful functions, methods, and classes that'll let you develop robust web components and web applications.

The developers of MooTools strongly believe in applying Object-Oriented Programming (OOP) principles to JavaScript, a structural programming language. Since everything in JavaScript is an object, MooTools provides a cleaner, easier, and more elegant way to manipulate the object to our will. MooTools also helps make the JavaScript code cross-browser compatible.

 

What is MooTools?


MooTools (which stands for My Object-Oriented "JavaScript" Tools) is a lightweight, modular, object-oriented JavaScript framework. It greatly speeds up and enhances the development cycle of feature-rich Ajax/JavaScript web applications. Created by Valerio Proietti—who originally intended it to be an extension to the Prototype JavaScript framework—MooTools has since grown into an independent, open-source, and very robust JavaScript framework with a solid team of core developers and thousands of users who support, contribute, and rabidly evangelize the project.

MooTools, in essence, abstracts normal JavaScript code so that you can write more terse and elegant client-side scripts. It has a host of useful functions, methods, and classes that'll let you develop robust web components and web applications.

The developers of MooTools strongly believe in applying Object-Oriented Programming (OOP) principles to JavaScript, a structural programming language. Since everything in JavaScript is an object, MooTools provides a cleaner, easier, and more elegant way to manipulate the object to our will. MooTools also helps make the JavaScript code cross-browser compatible.

 

Why use MooTools?


I've already mentioned that JavaScript isn't perfect; it's a language that's unintuitive at times and doesn't have a lot of native functions and methods to deal with modern user demands.

For example, Ajax is all the rage these days; the concept of Ajax allows us to communicate with our server-side scripts asynchronously. We heftily rely on Ajax requests and responses to give users an uninterrupted experience as we update the Document Object Model (DOM) behind the scenes after he or she performs an action such as submitting a web form or adding an item to their shopping cart.

If all of that sounds complicated and seems like it would take an insurmountable heap of JavaScript code to write, then you're right.

If you believe that MooTools will save you a lot of time and will help you write more efficient and terse JavaScript, then you're two for two!

Let's look at the advantages of using MooTools.

The advantages of using MooTools

There are many benefits to be had from learning and using MooTools.

Writing terse and elegant code

I think most would agree that what makes coding in JavaScript awful is stuff like browser quirks and non-standard behavior. In addition, it's very long-winded and even simple operations can sometimes take several lines of code to author because the language is very lightweight.

MooTools, like many of the other JS frameworks, aims at allowing web developers to write complicated procedures with clean, reusable, and understandable code. Not only will this improve the speed at which you complete your projects, but it also makes your code easier to read and maintain.

Extending native JavaScript

There are many functions and methods that web developers think JavaScript should have. For example, Ajax can be challenging because there are no set standards to working with it in JavaScript. MooTools attempts to address these missing parts in JavaScript by providing web developers with a set of standardized and useful classes, methods, and functions.

For example, to address the lack of an Ajax class in JavaScript, MooTools has the Request class which deals with operations involving XMLHttpRequest objects.

MooTools also has a variety of utility functions and methods that are extremely helpful on many occasions, like the $each() function which allows you to easily loop through objects such as non-regular arrays or function arguments, and the addEvent method which attaches event listeners to page objects so that we can react to user actions like mouseovers and mouse clicks.

Cross-browser compatibility

JavaScript has to run in a wide array of environments such as web browsers. Unlike server-side scripting languages like PHP and Python, where the server is responsible for compiling and interpreting your code, JavaScript is different in that the web browser interprets your code. Web browsers all have different quirks and ways of interpreting JavaScript, resulting in countless hours of debugging and browser testing.

MooTools handles these browser quirks for you. For example, web browsers have different ways of dealing with Ajax requests. Internet Explorer 6 has the ActiveX object while Mozilla-based browsers like Firefox have the XMLHttpRequest class.

Traditionally, whenever you create an Ajax request object in JavaScipt, you would have to check first which web browser the user is using. Thus, creating Ajax request objects results in a lot of if statements and browser-sniffing.

For example, this is one way of creating an Ajax request object in JavaScript:

var request;
//Try Compatible Browser
if ( window.XMLHttpRequest ) {
request = new XMLHttpRequest();
}
//Try IE6
else if (window.ActiveXObject) { // IE
request = new ActiveXObject("Microsoft.XMLHTTP");
}
<... More browsers here...>
else { //Code that deals with the event that a browser doesn't support XMLHttpRequest objects
document.write('Browser is unsupported');
}

In MooTools, you can forego all of that browser-sniffing. All you have to do to create an XMLHttpRequest object is the following code:

var myRequest = new Request([insert arguments here]);

There are two important things to note here:

  • You've just saved a ton of code to write

  • The request object you created will function the same way in all browsers

MooTools officially fully-supports and tests in the following web browsers (though it's very likely that it'll work perfectly in most other web browsers):

  • Safari 2+

  • Internet Explorer 6+

  • Firefox 2+ (and browsers based on gecko)

  • Opera 9+

Working with the Document Object Model

A defining feature of most JavaScript frameworks and libraries is that they provide you with a set of useful tools for working with the Document Object Model. Traversing and manipulating the DOM in JavaScript can take massive amounts of code and can be unintuitive to many web developers (not to mention having to deal with browser quirks that can add to the length and development time of your functions).

MooTools has an intuitive syntax for selecting and working on page objects.

For example, if you want to select all the<a> hyperlinks with a class of big that links to a .jpg file in a web page, it only takes a line of code:

var jpgLinks = $$('a.big[href$=.jpg]');

This line of code creates an array called jpgLinks containing the aforementioned set of hyperlinks.

In ordinary JavaScript, this same complex selection operation would involve several for loops and regular expression matching to accomplish. Modern browsers, such as Safari 4, FireFox 3.5, and IE8 (only CSS 2.1 compliant), are slowly catching up by implementing document.querySelector and document.querySelectorAll methods to simplify things.

The advantage of using open-source projects

Remember the saying, "Two heads are better than one"? Now multiply that two by several magnitudes of a thousand and that's the number of developers that constantly review, use, and contribute to the MooTools project.

MooTools leverages the collective knowledge and skills of thousands of MooTools users worldwide. Therefore, when a new bug is discovered, it is quickly reported and addressed. Also, you'll encounter some of the most efficient JavaScript code written in MooTools because it has been widely tested and inspected by MooTools users and the MooTools development team.

By using MooTools, you'll have access to a tried-and-tested JavaScript code base.

 

Downloading and installing MooTools


The first thing we need to do is download a copy of MooTools from the official MooTools website (http://www.mootools.net).

Note

It's important to note that, at the time of this writing, http://www.mootools.com is not associated with MooTools. If you've mistakenly navigated to mootools.com, don't worry, MooTools is alive and well. A simple Google search for "mootools" should result in http://mootools.net/.

What's great about MooTools is that it's extremely modular. You can—as I fondly refer to it—roll your own version of it by downloading only the components that you're going to use. This is important if you want to keep your web applications as light as possible.

For the purpose of this book, you should download the entire MooTools Core so that we can make sure we're all in the same page.

 

Time for action—downloading and installing the MooTools Core


The following steps will help you to download and install MooTools Core:

  1. Go to the MooTools Download page located at http://mootools.net/download. You'll see three options, choose the Uncompressed version.

  2. Create an HTML document, call it whatever you want, but I'll call mine index.html, as shown:

  3. Install MooTools by referencing it in the<head> of your HTML document with the following code:

    <script type="text/javascript" src="mootools-1.2.1-core-nc.js"></script>
    

    Right below the MooTools script reference, place the following block of code:

    <script type="text/javascript"> window.addEvent('domready', function() { alert("Hello World!"); }); </script>
    
  4. Test your code by opening your HTML document in your favorite web browser. If everything went according to plan, you should see something like this:

What just happened?

We've just downloaded and installed MooTools by referencing it in an HTML document that we created and then tested to see if we referenced the file correctly by writing a line of JavaScript that displays "Hello World" in an alert box.

For your reference, your HTML markup should look similar to the following:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Installing MooTools</title>
<script type="text/javascript" src="mootools-1.2.1-core-nc.js"> </script>
<script type="text/javascript">
window.addEvent('domready', function() {
alert("Hello World!");
});
</script>
</head>
<body>
</body>
</html>

If all went well, congratulations! You're on your way to becoming a MooTools rockstar!

Different MooTools downloads

When you went to the MooTools download page, you had three options: YUI Compressor, JSMin, and Uncompressed. These options have the same source code and differ only in the source code format. The YUI Compressor and JSMin versions are compressed. They are smaller in file size because unnecessary characters (such as those involved in code formatting, like tabs, extra spaces, and inline comments) have been removed.

The process of removing extraneous characters in the source code is called Minification. The trade-off in minifying your source code is that it's virtually unreadable, so we downloaded the Uncompressed version, in case you wanted to see how MooTools works by studying the source code.

The domready event listener

When writing MooTools code, you will often want to execute the code as soon as possible, otherwise it'll wait until other webpage components are loaded before it runs.

Let's take a closer look at the code we wrote earlier:

window.addEvent('domready', function() {
alert('Hello World');
});

In this block of code, we used the addEvent method and we tell it to watch out for the event that the window's DOM is ready ('domready'). Once the DOM is ready, we ask the method to run the following function:

function() {
alert("Hello World");
}

We will discuss the MooTools syntax and concepts in detail in Chapter 2, but for now, let's just say that all code we write throughout this book will be wrapped inside the domready event listener so they are executed as soon as possible.

 

Rolling your own MooTools


MooTools is one of the few JavaScript frameworks that come in different components; it has a very modular design—it is divided into several interdependent parts. Because of its modularity, we're able to pick and choose which parts of MooTools we want. However, if you have a project that doesn't use all of the MooTools components, then it's a good practice to only include the components that you need to reduce page weight and improve response times.

MooTools is organized into two major parts: the MooTools Core and MooTools More (plugins that extend MooTools). Let's take a look at these two components.

MooTools Core

Let's explore the MooTools Core by using the MooTools Core Builder on the official MooTools website. This will give us a basic understanding of the MooTools Core file structure.

 

Time for action—exploring the MooTools Core Builder


To explore the MooTools Core Builder, perform the following steps:

  1. Go to the MooTools Core Builder webpage by navigating to: http://mootools.net/core.

  2. Notice that the MooTools Core is subdivided into 7 sections. Each section has 2 to 6 JavaScript libraries associated with it. Take the time to read each description to help you get a better understanding of what each file does.

  3. Click on the Event component. Notice that several other components were automatically selected for you. This ensures that you also include the dependency files that are required for the Event component to run.

  4. Notice the different compression types. YUI Compressor is selected by default.

What just happened?

We just covered how to roll your own MooTools Core file and learned about the MooTools Core structure by exploring the MooTools Core builder. Once you're comfortable with how MooTools works, you should use the MooTools Core Builder to create a MooTools Core file that includes only the components you need.

Have a go hero explore the MooTools Core Builder output

Try to download the previous example with the Events component checked. After downloading your own version of the MooTools Core, open the file in your favorite text editor. Also open the MooTools Core file that you downloaded earlier. Notice that the one you just downloaded is significantly shorter; that's because you only downloaded the Events component and its dependency files.

The entire uncompressed MooTools Core is close to 4,000 lines long (and has a file size of 96 KB).

In comparison, the Core Builder output where only Events and its dependencies are included is just a little over 1,000 lines of code (and weighing only 24 KB).

MooTools More

The second part of the MooTools framework is simply called More. As the name implies, it is a collection of useful plugins, functions, classes, and methods that extends the MooTools Core.

 

Time for action—exploring the MooTools More Builder


To explore through the MooTools More Builder, perform the following steps

  1. Go to the MooTools More Builder page: http://mootools.net/more.

  2. You'll see the same interface as the MooTools Core Builder. Take some time to read the descriptions of each component.

What just happened?

You've just learned where to download the More components of MooTools. This knowledge will come into play in later chapters when we utilize these plugins in our code.

 

The API concept


MooTools is designed in such a way that instead of modifying the MooTools Core files, you use its API (Application Programming Interface) to utilize MooTools function. This makes MooTools easier to maintain your projects and makes it easily extensible.

A plugin is a JavaScript file that's dependent on MooTools but is not part of the standard MooTools code base. We'll learn about writing plugins in a later chapter, but for now, just think of plugins as MooTools extensions that do a specific function, such as hiding and showing a page element or managing browser cookies.

Note

It is important to note that—unless you know exactly what you're doing—you shouldn't modify the MooTools Core files. Even if you know what you're doing, it's best to keep the file "as is" so that it's standardized and can be easily updated.

 

MooTools resources


In order to take full advantage of MooTools, you should check out these excellent resources:

MooTools Docs

MooTools Docs (http://mootools.net/docs/) contains the official MooTools documentation. Created by the MooTools team, it's the most comprehensive online resource for MooTools syntax and usage. As you write in MooTools, you'll find that this is a handy resource to have open for quickly finding references to particular MooTools code.

MooTools Users Google groups

The MooTools Users Google groups (http://groups.google.com/group/mootools-users) is a discussion group on the topic of MooTools. You'll find a variety of topics here and if you run into specific MooTools problems, it's a great place to seek help.

mooforum

mooforum (http://www.mooforum.net/) is the unofficial forum for MooTools. If you're looking for help on specific things or simply want to interact with other MooTools developers, you should sign up for a free user account.

The MooTorial

The MooTorial (http://mootorial.com/wiki/) is an online wiki-style tutorial on the MooTools framework written by Aaron Newton. It's a good starting point for learning the basics of the MooTools framework and is a great online supplement to the things you learn throughout this book.

 

Summary


In this chapter we specifically covered:

  • What MooTools is and some of the advantages of using MooTools

  • How to download and install MooTools

  • The MooTools Core and More Builders

  • Online resources about MooTools

We also learned that all of our MooTools code will go inside the window.addEvent('domready', function) method, so that they can run as soon as the DOM is ready. In addition, we talked a little bit about the API concept and how we shouldn't modify the MooTools Core files.

Now that we've learned a little bit about MooTools, we're ready to delve into the MooTools syntax and concepts, which is the topic of the next chapter.

About the Authors

  • Jacob Gube

    Jacob Gube is a massive MooTools developer. He is the Founder and Chief Editor of Six Revisions, a website dedicated to web developers and web designers. He's also written for other popular web publications such as Read Write Web and Smashing Magazine discussing web technologies and development. A web professional for 8 years, Jacob is an in-house web developer specializing in distance-learning education and web accessibility, using PHP, MooTools, and jQuery to get the job done.

    Browse publications by this author
  • Garrick Cheung

    Garrick Cheung is a designer-developer and a member of the official Mootools Community team. He's currently a Senior Technical Producer for CBS Interactive developing for sites such as GameSpot.com, TV.com and MP3.com. He's passionate about code optimization and loves to teach and develop in MooTools. Garrick also writes about code and development at his site, http://www.garrickcheung.com.

    Browse publications by this author
Book Title
Unlock this full book FREE 10 day trial
Start Free Trial