MooTool: Understanding the Foundational Basics

Exclusive offer: get 50% off this eBook here
MooTools 1.3 Cookbook

MooTools 1.3 Cookbook — Save 50%

Over 110 highly effective recipes to turbo-charge the user interface of any web-enabled Internet application and web page

$26.99    $13.50
by Jay Larry G. Johnston | August 2011 | Open Source

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.

In this article by Jay Larry G. Johnston, author of MooTools 1.3 Cookbook, we will learn foundational MooTool basics like including MooTools in HTML, making and looping over arrays, grabbing elements, and dragging items.

 

MooTools 1.3 Cookbook

MooTools 1.3 Cookbook

Over 110 highly effective recipes to turbo-charge the user interface of any web-enabled Internet application and web page

        Read more about this book      

(For more resources on Mootools, see here.)

MooTroduction

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).

 

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

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.

How to do it...

This is the basic HTML framework within which all recipes will be launched.

<!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"/>

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='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="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>

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.

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.

 

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.

(Move the mouse over the image to enlarge.)

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.

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.

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='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="mootools-1.3.0.js">
</script-->
<!--we've got ours commented out so that we can use
google's here:-->

<script src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="https://www.google.com/jsapi?key=OUR-KEY-HERE"
type="text/javascript"></script>
// the full src path is truncated for display here
<script src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="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='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="mootools-1.3.0.js">
</script-->
<!--we've got ours commented out so that we can use google's
here:-->
<script src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="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 via http. 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.

Avoid mixing http and https resources; if using a secure site, opt for a local load of MooTools or use Google Library over HTTPS.

 

MooTools 1.3 Cookbook Over 110 highly effective recipes to turbo-charge the user interface of any web-enabled Internet application and web page
Published: July 2011
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

 

        Read more about this book      

(For more resources on Mootools, see here.)

 

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='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="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, 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()

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().

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>

 

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='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="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: 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='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="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.

 

MooTools 1.3 Cookbook Over 110 highly effective recipes to turbo-charge the user interface of any web-enabled Internet application and web page
Published: July 2011
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

 

        Read more about this book      

(For more resources on Mootools, see here.)

 

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!

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='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="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='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="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='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="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.

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.

 

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='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="mootools-1.3.0.js"></script>

<!-- we need the more, with the core! -->
<script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="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/.

Summary

In this article we took a look at the foundational MooTool basics.


Further resources on this subject:


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.

Books From Packt


iPhone JavaScript Cookbook
iPhone JavaScript Cookbook

Apache Wicket Cookbook
Apache Wicket Cookbook

Joomla! 1.5 JavaScript jQuery
Joomla! 1.5 JavaScript jQuery

Java EE 6 with GlassFish 3 Application Server
Java EE 6 with GlassFish 3 Application Server

JavaScript Testing Beginner's Guide
JavaScript Testing Beginner's Guide

Apache Maven 3 Cookbook
Apache Maven 3 Cookbook

NetBeans IDE 7 Cookbook
NetBeans IDE 7 Cookbook

Learning jQuery 1.3
Learning jQuery 1.3


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
u
x
y
n
z
s
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software