MooTools 1.3 Cookbook

By Jay Larry G. Johnston
  • 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. Oldies-but-Goodies: Foundational Moo

About this book

MooTools is a JavaScript framework that abstracts the JavaScript language. JavaScript itself, complex in syntax, provides the tools to write a layer of content interaction for each different browser. MooTools abstracts those individual, browser-specific layers to allow cross-browser scripting in an easy-to-read and easy-to-remember syntax.

Animation and interaction, once the domain of Flash, are being taken by storm by the MooTools JavaScript framework, which can cause size, shape, color, and opacity to transition smoothly. Discover how to use AJAX to bring data to today's web page users who demand interactivity without clunky page refreshes. When searching for animation and interactivity solutions that work, MooTools 1.3 Cookbook has individual, reusable code examples that get you running fast!

MooTools 1.3 Cookbook readies programmers to animate, perform AJAX, and attach event listeners in a simple format where each section provides a clear and cross-browser compatible sketch of how to solve a problem, whether reading from beginning to finish or browsing directly to a particular recipe solution.

MooTools 1.3 Cookbook provides instant solutions to MooTools problems – whatever you want to do with MooTools, this book will tell you how to do it.

MooTools 1.3 Cookbook is presented in a progressive order that builds concepts and ideas, while simultaneously being a collection of powerful individual, standalone, recipe solutions.

Publication date:
July 2011
Publisher
Packt
Pages
276
ISBN
9781849515689

 

Chapter 1. Oldies-but-Goodies: Foundational Moo

Foundational MooTool basics top the record charts both in the good old days and in this chapter: MooTool versions, documentation, and hosting:

  • Elements, arrays, and objects

  • Flat craziness like anonymous functions and arrays!

 

MooTroduction


All Packt Publishing Cookbook Series books are meant to be read without procedural constraint. That means, we can open any page in the book and just start mooing. This book, being a cookbook, follows that crucial precept while also harboring a secret agenda to move from smaller concepts to larger concepts for the benefit of any potentially existing procedural readers. Those of us that may be new to these concepts will benefit greatly from this chapter.

MooTools was conceived by Valerio Proietti and copy written under MIT License in 2006. We send a great round of roaring applause to Valerio for creating the Moo.FX (My Object Oriented Effects) plugin for Prototype, a JavaScript abstraction library. That work gave life to an arguably more effects-oriented (and highly extensible) abstraction layer of its own: MooTools (My Object Oriented Tools).

See also

Find more information about Moo.FX at http://moofx.mad4milk.net/. The link labeled GET MOO.FX FOR MOOTOOLS leads us to MooTools, which is exactly what we are delving into; so we continue, confident that with MooTools, we are getting what Moo.FX has become.

 

Knowing our MooTools version


This recipe is an introduction to the different MooTools versions and how to be sure we are coding in the right version.

Getting ready

Note

Not all are equal nor are backwards compatible!

The biggest switch in compatibility came between MooTools 1.1 and MooTools 1.2. This minor version change caused clamor in the community given the rather major changes included. In our experience, we find that 1.2 and 1.3 MooTool scripts play well together while 1.0 and 1.1 scripts tend to be agreeable as well. However, Moo's popularity spiked with version 1.1, and well-used scripts written with 1.0, like MooTabs, were upgraded to 1.1 when released. The exact note in Google Libraries for the version difference between 1.1 and 1.2 reads:

Since 1.1 versions are not compatible with 1.2 versions, specifying version "1" will map to the latest 1.1 version (currently 1.1.2).

MooTools 1.1.1 has inline comments, which cause the uncompressed version to be about 180% larger than version 1.2.5 and 130% larger than the 1.3.0 release. When compressed, with YUI compression, 1.1 and 1.2 weigh in at about 65K while 1.3.0 with the CSS3 selectors is a modest 85K. In the code snippets, the compressed versions are denoted with a c.js file ending.

Two great additions in 1.3.0 that account for most of the difference in size from 1.2.5 are Slick.Parser and Slick.Finder. We may not need CSS3 parsing; so we may download the MooTools Core with only the particular class or classes we need. Browse http://mootools.net/core/ and pick and choose the classes needed for the project. We should note that the best practice is to download all modules during development and pare down to what is needed when taking an application into production.

When we are more concerned with functionality than we are with performance and have routines that require backwards compatibility with MooTools 1.1, we can download the 1.2.5 version with the 1.1 classes from the MooTools download page at http://mootools.net/download. The latest MooTools version as of authoring is 1.3.0. All scripts within this cookbook are built and tested using MooTools version 1.3.0 as hosted by Google Libraries (more to follow on that in this chapter).

How to do it...

This is the basic HTML framework within which all recipes of this book will be launched and comprises the first recipe of the book:

<!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>
<title>MooTools Recipes</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />

Tip

Note that the portion above is necessary but is not included in the other recipes to save space. Please do always include a DOCTYPE, and opening HTML, HEAD, TITLE, and META tag for the HTTP-EQUIV and CONTENT.

<script type="text/javascript" src="mootools-1.3.0.js"></script>
</head>
<body>
<noscript>Your Browser has JavaScript Disabled. Please use industry best practices for coding in JavaScript; letting users know they are missing out is crucial!</noscript>
<script type="text/javascript">
// best practice: ALWAYS include a NOSCRIPT tag!
var mooversion = MooTools.version;
var msg = 'version: '+mooversion;
document.write(msg);
// just for fun:
var question = 'Use MooTools version '+msg+'?';
var yes = 'It is as you have requested!';
var no = "Please change the mootools source attribute in HTML->head->script.";
// give 'em ham
alert((confirm(question)?yes:no));
</script>
</body>
</html>

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

How it works...

Inclusion of external libraries like MooTools is usually handled within the HEAD element of the HTML document. The NOSCRIPT tag will only be read by browsers that have their JavaScript disabled. The SCRIPT tag may be placed directly within the layout of the page.

There's more...

Using the XHTML doctype (or any doctype for that matter) allows your HTML to validate, helps browsers parse your pages faster, and helps the Dynamic Object Model (DOM) behave consistently. When our HTML does not validate, our JavaScript errors will be more random and difficult to solve.

Note

Many seasoned developers have settled upon a favorite doctype. This allows them to become familiar with the ad-nauseam of cross browser oddities associated with that particular doctype. To further delve into doctypes, quirksmode, and other HTML specification esoterica, the heavily trafficked http://www.quirksmode.org/css/quirksmode.html provides an easy-to-follow and complete discourse.

See also

Be sure we are familiar with how non-sighted users browse our pages. We can make others' lives very difficult in the same stroke that we as programmers call user friendly. Check out the American Disabilities Act, ADA website for more information.

 

Finding MooTools documentation both new and old


Browsing http://mootools.net/docs/core will afford us the opportunity to use the version of our choice. The 1.2/1.3 demonstrations at the time of writing are expanding nicely. Tabs in the demonstrations at http://mootools.net/demos display each of the important elements of the demonstration.

MooTools had a major split at the minor revision number of 1.1. If working on a legacy project that still implements the deprecated MooTools version 1.1, take a shortcut to http://docs111.mootools.net.

Note

Copying the demonstrations line-for-line, without studying them to see how they work, may afford our project the opportunity to become malicious code.

 

Using Google Library's MooTools scripts


Let Google maintain the core files and provide the bandwidth to serve them.

Getting ready

Google is leading the way in helping MooTools developers save time in the arenas of development, maintenance, and hosting by working together with the MooTools developers to host and deliver compressed and uncompressed versions of MooTools to our website visitors. Hosting on their servers eliminates the resources required to host, bandwidth required to deliver, and developer time required to maintain the requested, fully patched, and up-to-date version.

Note

Usually we link to a minor version of a library to prevent major version changes that could cause unexpected behavior in our production code.

Google API keys that are required in the documentation to use Google Library can be easily and quickly obtained at: http://code.google.com/apis/libraries/devguide.html#sign_up_for_an_api_key.

How to do it...

Once you have the API Key, use the script tag method to include MooTools. For more information on loading the JavaScript API see http://code.google.com/apis/libraries/devguide.html#load_the_javascript_api_and_ajax_search_module.

<!--script type="text/javascript" src="mootools-1.3.0.js">
</script-->
<!--we've got ours commented out so that we can use google's here:-->
<script src="https://www.google.com/jsapi?key=OUR-KEY-HERE" type="text/javascript"></script>
// the full src path is truncated for display here
<script src="https://ajax.googleapis.com/.../mootools-yui-compressed.js" type="text/javascript"></script>
</head>
<body>
<noscript>JavaScript is disabled.</noscript>
<script type="text/javascript">
var mooversion = MooTools.version;
var msg = 'MooTools version: '+mooversion+' from Google';
// show the msg in two different ways (just because)
document.write(msg);
alert(msg);
</script>

Using google.load(), which is available to us when we include the Google Library API, we can make the inclusion code a bit more readable. See the line below that includes the string jsapi?key=. We replace OUR-KEY-HERE with our API key, which is tied to our domain name so Google can contact us if they detect a problem:

<!--script type="text/javascript" src="mootools-1.3.0.js"></script-->
<!--we've got ours commented out so that we can use google's here:-->
<script src="https://www.google.com/jsapi?key=OUR-KEY-HERE" type="text/javascript"></script>
<script type="text/javascript">
google.load("mootools", "1.2.5");
</script>
</head>
<body>
<noscript>JavaScript is disabled.</noscript>
<script type="text/javascript">
var mooversion = MooTools.version;
var msg = 'MooTools version: '+mooversion+' from Google';
// show the msg in two different ways (just because)
document.write(msg);
alert(msg);
</script>

How it works...

There are several competing factors that go into the decision to use a direct load or dynamic load via google.load():

  • Are we loading more than one library?

  • Are our visitors using other sites that include this dynamic load?

  • Can our page benefit from parallel loading?

  • Do we need to provide a secure environment?

There's more...

If we are only loading one library, a direct load or local load will almost assuredly benchmark faster than a dynamic load. However, this can be untrue when browser accelerator techniques, most specifically browser caching, come into play. If our web server is sending no-cache headers, then dynamic load, or even direct load, as opposed to a local load, will allow the browser to cache the Google code and reduce our page load time. If our page is making a number of requests to our web server, it may be possible to have the browser waiting on a response from the server. In this instance, parallel loading from another website can allow those requests that the browser can handle in parallel to continue during such a delay.

We need to also take a look at how secure websites function with non-secure, external includes.

Many of us are familiar with the errors that can occur when a secure website is loaded with an external (or internal) resource that is not provided viahttp. The browser can pop up an alert message that can be very concerning and lose the confidence of our visitors. Also, it is common to have some sort of negative indicator in the address bar or in the status bar that alerts visitors that not all resources on the page are secure.

Note

Avoid mixinghttp andhttps resources; if using a secure site, opt for a local load of MooTools or use Google Library over HTTPS.

 

Injecting Hello World into an HTML DIV


Let us add an element to the HTML Document Object Model (DOM).

Getting ready

There is no oldie that is more goodie than greeting the world around us. There is an elemental power to our first Hello World, a power that proclaims, "We have the power to code syntactically correct. We have the power to change things on the screen. We have the power to accomplish business goals using this language. And, we are friendly and outgoing; 'Hello'."

How to do it...

Here is an example that demonstrates MooTools' syntax and power:

<script type="text/javascript" src="mootools-1.3.0.js"></script>
</head>
<body>
<div id="mycanvas">
Knock Knock, Who's there?
Hello, who?
</div>
<script type="text/javascript">
var whocanitbenow = 'Hello World!';
var readymsg = 'Okay to make the magic happen?';
if (confirm(readymsg,true,false)) {
// sexy part:
$('mycanvas').set('html',whocanitbenow);
} else {
// well, since they're being silly...
setTimeout(fallback_plan, 1000);
}
function fallback_plan() {
$('mycanvas').set( 'html', 'orange you glad there is a backup message?');
}
</script>

How it works...

So, as usual in our favorite MooTools cookbook, the alluring part is set with spacing above and below. Here is the 1, 2, 3 of what is happening in that nugget of goodness:

  • We use the MooTools dollar, $, to select our div

  • We use the MooTools method set()

  • We send two arguments to set()

    Note

    MooTools $ has a counterpart, the double dollar sign: $$, which is used for sending CSS selectors and returns a multiple element collection.

    The single $, originally reserved for grabbing DOM unique, id attributed elements takes no punctuation not already inherent in the name of the id attribute.

Using MooTools dollar not only empowers us with cross-browser compatible code to humbly abstract and replace the infamous, JavaScript built-in, getElementById() method to get the element, but it also enhances the returned object with Moo-methods like get() and set().

Tip

Using Multiple Frameworks

It is imperative to use document.id(<id>) instead of its alias, $(<id>), when working with multiple frameworks. Reviewing the Moo-source shows that document.id is used exclusively. When another framework is using the dollar syntax, MooTools attempts to sense that and not extend the object.

There's more...

The get() method returns the attribute or property value requested while the set() method takes the attribute/property argument and a value to which the property should change. In this example we could use $('mycanvas').set('text',whocanitbenow);. That would do the same thing as our example, since we have only altered text, but would prevent us from injecting HTML and would strip all existing HTML from our text.

We now see that our goal with this recipe is to try it out; be sure to change the whocanitbenow variable to something with HTML in it like this:

<script type="text/javascript">
var whocanitbenow = '<strong>Hello <em>World</em></strong>!';
var readymsg = 'Okay to make the magic happen?';
if (confirm(readymsg,true,false)) {
// "alluring" part:
$('mycanvas').set('html',whocanitbenow);
} else {
// well, since they're being silly...
setTimeout(fallback_plan, 1000);
}
function fallback_plan() {
$('mycanvas').set( 'html', 'orange you glad there is a backup message?');
}
</script>

See also

For more information on CSS selectors see http://www.w3.org/TR/CSS2/selector.html.

 

Storing a list of names in an array of values


In this recipe we will learn how to use a standard data structure called an Array to store a list of names or values.

Getting ready

To create an array, a storage element that holds a list of values, elements, or objects, we use the raw JavaScript Array object to define a literal array var myarray = [1, 2, 'my 3rd value'];. In our example, we first declare our array; it is in an empty state, then we call upon either raw JavaScript's push() array object method or MooTools' extension of the array native include(), based on the ternary output, to add our string value to the array.

How to do it...

Add items to an array. Allow or disallow the addition of duplicate items with a switch in the form.

<script type="text/javascript" src="mootools-1.3.0.js"></script>
</head>
<body>
<form action="" method="get">
<input type="text" id="myitem"/>
Ignore if already in the array?
<input type="checkbox" id="unique"/>
<input type="button" id="mybutton"
value="Add This"
onclick="store_item_in_array();"/>
</form>
<script type="text/javascript">
// declare the array
var myarray = [];
// an array-dedicated utility function to add elements
function store_item_in_array() {
// use the $ object to get element with id "myitem"
var myitem = $('myitem').value;
// ternary operators can save a lot of space
var ischecked = $('unique').get('checked');
var unique = (ischecked) ? 1 : 0;
if (!unique) {
// (A) add an item to an array with raw JavaScript
myarray.push(myitem);
} else {
// (B) add an item to an array, but make it moonique
myarray.include(myitem);
}
alert('Length of Array: '+myarray.length);
}
</script>

How it works...

Much like $, arrays are infused with methods that extend their capability. This snippet calls the JavaScript inherent push(), which post-pends the single argument to the array, like this: var myarray.push('myvalue');.

Note

NOTE: The JavaScript array object will hold much more than string values: it can hold integers, objects, even other array objects to create multi-dimensional arrays!

MooTools has further extended the array prototype by adding new, useful methods. The method used here is called include(), which works identically both in syntax and in function to push(); however, it adds a duplicate value check to the incoming argument. If one or more values present are matched, the function does not add a value to the array.

There's more

We should open up the uncompressed version of our MooTools and search for the phrase "include". We can quickly see how include() is an abstraction that enhances push().

 

Looping over an array of names and saying "Hello" to all of them


In this recipe we will be looping over an array of names and saying "Hello" to each of them.

Getting ready

To initialize our list of names, we look to the United States' President, Barack Obama, who did an interview in 2008 with Rolling Stone magazine and mentioned the oldies musicians found on his iPod. Let's loop over that list and say, 'Hello' to each of them.

How to do it...

Use literal JavaScript array definition to put the array values in an object array, var obamas_oldies = ['Stevie Wonder', 'a lot of Bob Dylan', 'a lot of Rolling Stones', 'a lot of Miles Davis', 'John Coltrane'];Using either of the other types of array object instantiation syntax would not affect this example.

<script type="text/javascript" src="mootools-1.3.0.js"></script>
</head>
<body>
Hello Bulletin Board:<br/>
<div id="hello_board"></div>
<script type="text/javascript">
var oldies = ['Stevie Wonder', 'a lot of Bob Dylan', 'a lot of Rolling Stones', 'a lot of Miles Davis', 'John Coltrane'];
var hb = $('hello_board');
// iterating an array using a bound function
obamas_oldies.each(
function(oldie, index){
hb.set('html',hb.get('html')+'<br/>Hello '+oldie+', you are number '+index+' on the Obama playlist!');
}
);
</script>

How it works...

Once we have an array of values, it is inevitable that we will need to loop over them. Iterating through array values is made mooch more simple by our JavaScript abstraction layer's iteration methods, each() and forEach(), which extend when a browser does not have, built-in, a forEach() iterator. The two methods are identical.

In the example, for effect, a line break is separating the each() opening and the beginning of the mandatory first argument, the callback function. There does not need to be a space here; usually, programmers write the first line (including the optional secondary argument) as such:

obamas_oldies.each(function(oldie, index){

On the final line, the closing curly brace of the function and the closing parenthesis of the argument are nearly always sandwiched together:

});

The get() and set() method of the $-defined DOM object allow us to inject the HTML message(s).

See also

When we return to the MooTools online documentation to learn more about the get() and set() methods, we really prepare ourselves to become MooTool aficionados, ready at a moment's notice to help a friend or coworker with their Moo-predicaments.

 

Doing more with a list of names by creating an object


Objects, like arrays, are used to store information; however, they can be used to also store functionality. When a value is stored in an object, it is referred to as a property. When functionality is embedded in an object, it is called a method. This recipe shows how to use properties and methods of objects in MooTools.

Getting ready

An object is a reusable, client-side, storage syntax. In other words, it's like a function because we can call it from anywhere, but it is also like a miniature, temporary database, too!

Note

We can make a parallelism between instances of an object and rows of a database. That imagery can be furthered by likening columns, fields of the row, to properties of the object.

In raw JavaScript, one way to add a property to an object is with the dot operator like this: my_object.name = 'Jay LG Johnston';. Unfortunately, that does not allow us to reuse the object. In other words, if our code was used in another place, we would have to copy and paste the entire block.

Defining built-in functions, called methods on this kind of singleton class is possible, but our storage mechanism will only ever hold one row, at any given time. Our code in the singleton could not be used without copying and pasting it to other singleton objects. More explanation follows.

How to do it...

Instead of creating our object as a single instance, we create a template object using the MooTools Class object. This abstraction allows us to use a more familiar syntax for creating our objects.

<script type="text/javascript" src="mootools-1.3.0.js"></script>
</head>
<body>
Hello Bulletin Board:<br/>
<div id="hello_board"></div>
<script type="text/javascript">
var hb = $('hello_board');
var my_object = new Class({
// object constructor
initialize: function(oldies_array){
this.oldies = oldies_array;
},
// object method
say_hello: function() {
this.oldies.each(
function(oldie, index){
hb.set('html',hb.get('html')+'<br/>Hello '+oldie+', you are number '+index+' on the playlist!');
}
);
hb.set('html',hb.get('html')+'<br/>');
}
});
var oldies = ['Stevie Wonder', 'a lot of Bob Dylan', 'a lot of Rolling Stones', 'a lot of Miles Davis', 'John Coltrane'];
var obama = new my_object(oldies);
obama.say_hello();
var oldies = ['George Thorogood', 'Dennis DeYoung', 'The Cyrkle'];
var other = new my_object(oldies);
other.say_hello();
</script>

How it works...

When we have a tiny storage mechanism to store our values with simple syntax, we can call internal methods on each instance of a templated object. Through code reuse like this, we can really bring value to our employers.

There's more...

This sort of code reuse is a feature of Object Oriented Programming (OOP). Let us now update our resumes for we know the basics of code reuse and must proclaim our ability to add value in the workplace.

The search engines have links to Wikipedia articles describing different design patterns in the OOP world. Knowing more about those patterns not only makes our code better but prepares us for those pesky interview questions.

 

Creating a pop-up alert upon clicking a DIV


Here we will learn how to use an event listener to pop up an alert box.

Getting ready

We are familiar with how to place an HTML attribute like onmouseover that will execute upon a user's mouse entering the space of the HTML element. This is a frequent method of creating roll-over actions for buttons on website navigation. When editing a website that has these code-heavy roll overs, it can be confusing how to alter the roll overs. They create quite a bit of code.

How to do it...

Now MooTools makes our lives easy; we see that MooTools itself is becoming an oldie-and-goodie. It is exciting to learn that using listeners, heretofore a jUnGlE of confusing syntax, is now as simple as calling the addEvent() method with which MooTools has extended our elements.

<script type="text/javascript" src="mootools-1.3.0.js"></script>
</head>
<body>
<div id="my_trigger" style="width:100px; height:100px; border:1px solid #BEBEBE; line-height:50px; text-align:center;">Click Me</div>
<script type="text/javascript">
var count = 0;
$('my_trigger').addEvent('click',function() {
$('my_trigger').set('html','Click Me<br/>'+(++count));
alert('Hello, please be aware that my_trigger has been clicked!');
});
</script>

How it works...

The addEvent() method takes two arguments (1) the event name and (2) the callback handler or function definition. Event names include all the common events defined by HTML; however, they each drop the "on"; for instance, instead of passing "onSubmit" as the event name, pass "submit": $('my_form').addEvent('submit',function() { return false; });.

The World Wide Web Consortium, W3C, publishes a plethora of information on events in HTML. While we might not have time to read all of it, being familiar with where it is allows us to seek out the answers to really advanced questions that will come up along the path of our development careers.

There's more...

In our example, we add an event function to my_form. Within that function we then make calls to the same element my_form. This can be reduced further by using a keyword that describes the element that is the owner of the executing function, this:

$('my_trigger').addEvent('click',function() { this.set('html','Click Me<br/>'+(++count));
...
 

Adding multiple event listeners to an HTML element


Listeners make an HTML element stand at the ready, waiting to do what it has been tasked with.

Getting ready

Once familiar with the built-in JavaScript and additional MooTool events that we can bind actions to, we note the addEvent() syntax from the previous recipe and move on to the more agile addEvents() syntax.

How to do it...

The syntax for adding multiple events is similar enough to adding a single event that one could nearly guess it. Look at this example to see how intuitive it is:

<script type="text/javascript" src="mootools-1.3.0.js"></script>
</head>
<body>
<div id="my_trigger" style="width:100px; height:100px; border:1px solid #BEBEBE; line-height:100px; text-align:center;"></div>
<script type="text/javascript">
$('my_trigger').addEvents({
'mouseover': function() {
this.set('html','MouseOver!');
},
'mouseout': function() {
this.set('html','MouseOut!');
},
'click': function() {
var width = (this.getStyle('border-width'). toInt()==1) ? '5px' : '1px';
this.setStyle('border-width',width);
}
});
</script>

How it works...

The syntax for adding multiple events is very similar to that of adding a single event. Remembering that addEvent() takes the event name and the function to execute, we can easily see that addEvents() takes the same two arguments, only in hashed form so that multiple event names can have individual functions applied to them.

There's more...

In our example, we have defined three events to listen for: onmouseover, onmouseout, and onclick. Remove the "on" prefix for events when using these functions.

Note

MooTools adds two important events that help to solve the event bubbling dilemma where each parent and children both report events causing them to fire more times than one would expect: mouseenter and mouseleave. These events were originally proprietary to Internet Explorer.

New to what we have seen so far in the book is Element.setStyle(). This method, along with its sibling, Element.getStyle(), do just as they suggest. They help us to get and set style properties. The syntax parallels that of addEvent() and addEvents().

Our goal for this chapter is to sit down and remove a lot of cut-and-paste code from one of our projects and replace with a very slick, object oriented roll over based on this recipe. Let's go!

 

Dragging an HTML element


HTML can be moved around on a page with a click-and-hold while moving the mouse.

Getting ready

MooTools has two libraries: Core and More. The Core contains code that is always used for every MooTools application and is found at http://mootools.net/core. There are many goodies that are oldie or otherwise in the MooTools More library: http://mootools.net/more.

In a previous recipe we profiled the sizes of different MooTools versions. There are different versions of MooTools More; nevertheless, we will be profiling only different selections for download of the 1.3.0 MooTools More library:

mootools_core-more-1.3.0.js 328K

mootools_core-more-1.3.0c.js 224K

mootools_core-more-nolocale-1.3.0.js 217K

mootools_core-more-nolocale-1.3.0c.js 137K

In the actual oldies, when 14.4K dial-up connections rocked our Mozilla Netscape worlds, 137K was enough of a boat anchor to cause a visitor to leave and never return. Fortunately, in this day of 500K skip-this-preview splash pages, if we are truly providing a fresh user interface, we may be forgiven for an extra 137K of library. Still, it is to everyone's benefit to selectively choose, from the MooTools More download page, only the More classes needed once a site goes into production.

In development, though, our scope may change rapidly, so let us get the whole shebang. One consideration we might make for development, to reduce our own code-refresh loop time, is to not include the Locale functions. Shown earlier are the compressed ("c.js") and non-compressed versions of the full More and the More minus the Locale functions.

How to do it...

<!-- we have to have the core, always -->
<script type="text/javascript" src="mootools-1.3.0.js"></script>
<!-- we need the more, with the core! -->
<script type="text/javascript" src="mootools-more-nolocale- 1.3.0.js"></script>
</head>
<body>
<div id="my_trigger" style="width:100px; height:100px; border:1px solid #BEBEBE; line-height:50px; text-align:center;">Drag Me</div>
<script type="text/javascript">
// show how easy it is to make a dragging object
var movin_object = new Drag.Move('my_trigger');
</script>

How it works...

Defining a Drag object is as simple as passing an element ID to the method Drag.move(). That method also takes a second argument, which is an object that itself can have properties and anonymous functions, which become the definitions of methods that enhance the individual dragging object.

There's more...

Events available to dragging objects include:

  • onSnap

  • onComplete

  • onDrop

  • onEnter

  • onLeave

See also

The MooTools site has several nice demonstrations of the Drag class. We are really familiar with those so that we have the best footing for expanding our own ideas on how to use them, not so that we can capitalize upon them in an as-is state. The link to the website is http://mootools.net/demos/.

 

Understanding MooTools ubiquitous anonymous functions


Functions have names, but anonymous functions do not; MooTools uses them everywhere.

Note

Anonymous functions are one-time use like disposable lighters. In MooTools, we use them to one-time define a method; reusable disposable functions!

Getting ready

To define and call an anonymous function raw JavaScript wraps a function in parentheses:

(function(){document.title=location.href;alert('done');})();

Nothing is returned, and the function is not assigned to a function identifier; when the () function syntax is appended, the function self-executes.

How to do it...

MooTools' use differs slightly in that we will pass this anonymous function as an argument to a MooTool object and bind it to an identifier; the anonymous syntax does not change.

<script type="text/javascript" src="mootools-1.3.0.js"></script>
</head>
<body>
<div id="my_trigger" style="width:100px; height:100px; border:1px solid #BEBEBE; line-height:50px; text-align:center;">Click Me</div>
<script type="text/javascript">
// (A) would change title, alerts done in true lisp style
//(function(){document.title=location.href;alert('done');})();
// (B) saves the anonymous function in a variable
var af = (function(){
document.title=location.href;
alert('done');
});
// (C) "calls" the anonymous function (commented out)
//af();
// (D) returns the function (and alerts its text)
//alert($lambda(af)); // note, lambda is deprecated
// (E) binds function to the click event on my_trigger
$('my_trigger').addEvent('click',
af
);
</script>

How it works...

  • A indicates a classical JavaScript style, anonymous, self-executing function.

  • B (used in our recipe) assigns a self-executing function to an identifier.

  • C in raw JavaScript would call the self-executing function.

  • D demonstrates deprecated usage of MooTools' $lambda object.

  • E (used in our recipe) passes the function to be bound to click events.

There's more...

Speaking in a strictly semantic world where anonymity is not compromised by that golden oldie 1984 and Orson Wells' cameras and dictatorial fiction, an anonymous function cannot be called more than once; it is defined, executed, and lost. Assigning it to an identifier would, in a pure discourse, render it no longer anonymous. Verily, the point of a recipe on anonymous functions is but to aid us in our understanding behind the science on how functions are passed to objects and then later executed as methods. Read up on more about what anonymous functions are on your favorite wiki site and send the author assertively argumentative proof as to the gamut of viewpoints regarding this subject.

 

Making an Ajax call


Getting ready

Asynchronous JavaScript and XML (Ajax) saves time by updating a page without refreshing it completely. Ajax has been around for a long time, with varied limits of browser support. It is safe to say that Google is most guilty of showing the world how easy it is to use.

How to do it...

Now with the MooTools abstraction layer's Request object, Ajax is child's play.

<script type="text/javascript" src="mootools-1.3.0.js"></script>
</head>
<body>
<form action="" method="get">
<input type="button" id="mybutton" value="Ajax!"
onclick="ajax_it();"/>
</form>
<script type="text/javascript">
var myJax = new Request({
url: '?',
onSuccess: function(response) {
alert('Success! Here is the response: ' +response);
}
});
function ajax_it() {
myJax.send();
}
</script>

How it works...

Switch the url property to that of the script that will process the Ajax request. Like any good recipe, it is important to switch out ingredients as the chef's needs arise, for instance, artificial sweeteners for sugar. In this snippet, the url variable, or to be more semantically correct, property of the myJax object is currently set to ?. This probably only has purpose in this academic setting. The usage in this case causes this page to request itself, and the result is that the page calls its own URL and displays the resulting source code.

There's more...

One great example of how to use Ajax to make our web pages more friendly is in conjunction with a user sign-up form. It can be frustrating for users to submit their form only to find out their desired username is in use.

Program the sign-up form's input field to make an Ajax call onkeyup. The returning value would be a Boolean that could be used to notify the user whether their choice was available or in use.

See also

Chapter 5, Mr. Clean Uses Ajax: Remote Asynchronous Calls is complete with Request(), Request.HTML, and Request.JSON examples.

About the Author

  • Jay Larry G. Johnston

    Jay's first web work was in 1996 for the United States Army where he served the 5/5 Battalion Headquarters with the 2nd Infantry Division in South Korea. Currently full time as Senior PHP Developer for ICGLink, Inc. managing high-end, custom development for the 2,000+ client base, Jay holds certifications in Linux, MySQL, and PHP5. Introduced to the MooTools framework in 2007 while on permanent contract at Marshall Space Flight Center, Jay has incorporated Moo into every single new development since and frequently writes canned moo-solutions for use within the company.

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