Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

July 21 2011

14:28

May 18 2011

18:47
Sponsored post
feedback2020-admin
04:05

February 01 2011

18:55

December 14 2010

13:03

October 20 2010

01:02

MooTools 1.3 Hits the Street

After almost a year in development, the MooTools team announced the release of version 1.3 with major notable enhancements.

Slick Selector Engine

The biggest update is the inclusion of the new Slick standalone selector engine. The engine was developed by Thomas Aylott, Fabio Costa and Valerio Proietti with accuracy and portability in mind, allowing the engine to not only provide MooTools developers with excellent selector support but also the ability for it to be included in other projects as well. The MooTools team created over 3,000 tests to ensure that even the most obscure scenarios were considered. The inclusion of Slick also allowed the team to extend the Element method to allow creation of DOM elements using complex CSS selector expressions. Very cool!

JAVASCRIPT:
var newElement = new Element('div#cow.moo.big[data-size=5]')

Core Updates

The MooTools team also focused on enhancing the core API in preparation for MooTools 2.0 by deprecated every $- prefixed function and nd moving those to the relevant natives namespaces:

We have revised the whole base of our library to speed up MooTools, to provide an even more beautiful API and to make our library future-proof. In order to reduce the amount of global variables we have moved all $-prefixed functions into their according namespace ($splat » Array.from, …). In short we think that with 1.3 you are getting the best MooTools experience ever.

New Build Manager

Building a new version of MooTools has always been easy using the builder and now it's been improved via the new Packager preprocessor which allows you to create custom MooTools builds from Github repositories. It handles code dependencies and already provides support for several MooTools plugins. The new Packager is a PHP 5.2+ library but can also be found as a Python app thanks to Aaron Newton's work.

MooTools Runner

To make sure that MooTools continues to adhere to the projects's specifications, Christoph Pojer & Arian Stolwijk spent some time over the summer building a new spec testing engine called MooTools Runner which has been adopted by all major MooTools projects - Core, More and Slick. The engine is based on Jasmine and runs all specs within just 2 seconds. In addition, code coverage was increased to about 95%, ensuring excellent test coverage for Core.

Download it!

Once you're ready, you can grab the latest version of MooTools or roll your own via the following links:

September 20 2010

19:00

August 26 2010

18:15

August 18 2010

12:05

July 27 2010

12:32

July 26 2010

17:45

July 10 2010

10:00

40 Seriously Awesome MooTools Tutorials and Plugins

MooTools is a lightweight, object-oriented and very popular framework for JavaScript, written in JavaScript which can spice up the interactivity and beauty of your site. User interface plays an important role in the success of any website; JavaScript, CSS and AJAX are commonly used to provide users the leisure of rich user interface over past few years. But using one of the most popular JavaScript libraries, MooTools you can add extra smoothness and interactivity in your website. In this post we have covered some MooTools tutorials and plugins which can be very handy if you are just entering in the world of MooTools.

1. How to Auto Caption Images Using MooTools


In this tutorial your will write a simple script that will select all images with the class of captioned, Take its title attribute or alt attribute and Display it right below the image.

Read Full Tutorial
Demo

2. Sexy Alert Box


Sexy Alert Box replaces old fashion and abruptly appearing alerts with good-looking ans smoothly appearing Alerts using MooTools 1.2 or up.

Read Full Tutorial
Demo

3. AJAX Username Availability Checker Using MooTools 1.2


Almost every website offering membership to its readers needs username availability checker to facilitate users in a way that they know if their desired username is available or already registered on the specific site. So here is a tutorial on how you can implement a username availability checker using MooTools 1.2.

Read Full Tutorial
Demo

4. AutoCompleter


You must have noticed Google giving suggestion about your search queries in a drop down. This Auto-completer script provide the same facility for text suggestion and completion using MooTools.

Read Full Tutorial
Demo

5. AutoGrow Textarea MooTools Plug-In


This MooTools plug-in expands a text-area as the user types something in it.  This version is based on the jQuery plug-in developed by Chrys Bader (www.chrysbader.com).

Read Download Plug-in
Demo

6. Background Animations Using MooTools


Mootools a JavaScript framework made animation very easy. This tutorial will show how you can use animated effect in your website.

Read Full Tutorial
Demo

7. Better Pull Quotes with MooTools


This tutorial will use MooTools to create a great-looking pull quotes which will automatically display quotes without repeating any content.

Read Full Tutorial
Demo

8. Create a Quick MooTools Slideshow with Preloading Images


This code will let you learn how to create a simple image slideshow using MooTools with the feature of pre-loading the images; which looks more elegant and enhance the pleasure of viewing the images.

Read Full Tutorial
Demo

9. Create a Simple, Powerful Product Highlighter with MooTools


In this tutorial we’ll be creating a flexible tool for highlighting the products or services available on your website using the MooTools; a JavaScript framework.

Read Full Tutorial
Demo

10. Create a Spectacular Photo Gallery with MooTools


In this tutorial, you will learn to combine many of MooTools’s features to create a nice and simple photo gallery.

Read Full Tutorial
Demo

11. Create a Sprited Navigation Menu Using CSS and MooTools


In this tutorial your will learn to create a sprited navigation menu using CSS and Mootools

Read Full Tutorial
Demo

12. Create an Animated Sliding Button Using MooTools

Every website should have attractive and good-looking buttons to gain the attention and attraction of readers. If you want to be a successful website owner you need to be creative and should not use the old style boring buttons. In this tutorial you will learn to create an animated sliding button using MooTools.

Read Full Tutorial
Demo

13. Create Snook-Style Navigation Using MooTools


This tutorial will teach how you can use an image and Mootools to create a slick mouse-over effect.

Read Full Tutorial
Demo

14. Create Twitter-Style Dropdowns Using MooTools


Well, everybody must have seen the drop-down login menu to twitter. This tutorial will teach you how you can duplicate that functionality of twitter like drop-down menu using MooTools.

Read Full Tutorial
Demo

15. Facebook Sliders With MooTools and CSS


This tutorial will explain how to create Facebook-style sliders that control the height, width, and opacity of an image.

Read Full Tutorial
Demo

16. FancyForm


FancyForm script replaces old checkboxes with the new interactive and flexible checkboxes with Tick being the sign for checked option and cross for the unchecked option.

Read Full Tutorial
Demo

17. iPhone-Style Passwords Using MooTools PassShark


In this tutorial you will learn how to create a iPhone-like password field, showing the most recently typed character and hiding previous per normal password fields.

Read Full Tutorial
Demo

18. JavaScript drop down menu using Mootools


Drop down menus are very important for any website layout and beauty. So in this tutorial you will learn to create a very easy and unobtrusive drop down menu using MooTools Core Build and the Fx.Slide.

Read Full Tutorial
Demo

19. Kroppr


Kroppr is an image cropping tool for your website that allows users to rotate, re-size and crop images with minor changes to your site.

Read Full Tutorial
Demo

20. Milkbox


Milkbox is a simple and sleek lightbox clone written for MooTools.

Read Full Tutorial
Demo

21. MooFlow


MooFlow give you a completely awesome browsing experience on your website, almost same as you get on apple.com for viewing the products.

Download
Demo

22. mooRainbow

Description
Download
Demo

23. mooSlide

mooSlide replaces common lightbox with Ajax one. You can have any type of content in it like HTML or FLASH, it can slide from top or bottom. It can be very handy to create beautiful sliding login panel.

Download
Demo

24. MooTools CountDown Plugin

I assume every one have used rapidshare at least for one time and had to wait for some seconds for the downloading starts. Using MooTools you can make a similar CountDown plugin by the use of which you can implement the same system that rapidshare is using.

Original Link
Demo

25. MooTools Kwicks Plugin


MooTools Kwick Plugin will enable you to have a hidden detail of an image displayed when you take your cursor on that image.

Original Link
Demo

26. MooTools Zoomer Plugin

Zoomer provides an elegant method for zooming in on large images.

Original Link
Demo

27. Morph Effect on mouseenter/mouseleave with Mootools


In this tutorial you will learn to add an elegant morph effect on unordered list on mouseover.  Demo can elaborate more about this tutorial.

Tutorial
Download
Demo

28. Sexy Animated Tabs Using MooTools

If you have less space and more content to display then you can use tab systems. This tutorial will show you how to create sexy and animated tabs which can handle lot of content in little space.

Read Full Tutorial
Demo

29. Sexy sliding JavaScript side bar menu using mootools


A sliding menu can help you to save a lot of space on your website. This tutorial will use MooTools to create a sexy sliding side bar menu with very smooth sliding effect.

Read Full Tutorial
Demo

30. Sliding Labels Using MooTools


This tutorial will teach you to create sliding labels using little jQuery code. Luckily the effect doesn’t require much MooTools code either!

Read Full Tutorial
Demo

31. Smooth Scrolling with MooTools Fx.SmoothScroll

Learn to create smooth scrolling effect using MooTools Fx.SmoothScroll.

Read Full Tutorial
Demo

32. TableGear


TableGear is a software package for working with data on the web. It is designed get your data into a web page, and let you work with it quickly and easily, the way you would in powerful desktop applications like Excel.

Download
Demo

33. Two CSS vertical menu with show/hide effects


This is a simple tutorial which will teach you to create two vertical menu with hide/shoe effect. One example will use Simple JavaScript and other will use MooTools.

Read Full Tutorial
Demo

34. Using CSS and Mootools to simulate Flash horizontal navigation effect


This tutorial explains how to use Mootools and pure CSS / HTML code to simulate a Flash (follow mouse) horizontal navigation effect.

Read Full Tutorial
Demo

35. Using MooTools to Instruct Google Analytics to Track Outbound Links

Google Analytical provides important information about your visitors and where they are coming from, and if you want to see what are the exit links then by using MooTools you can direct Google Analytic to track outbound links

36. Facebook-Style Modal Box Using MooTools


This tutorial will teach you to combine CSS, Facebook’s imagery and MooTools to create a stylish and lightweight Facebook like Modal Box.

Read Full Tutorial
Demo

37. SqueezeBox – Expandable Lightbox


SqeezeBox is an overly which is designed getting inspired from LightBox. It will display the images in the full size in the same window like LightBox.

Download
Demo

38. FancyUpload – Swiff meets Ajax


FancyUpload replaces unobtrusive, queued and multiple-file selection with a fancy animated progress bar. It is very easy to set up and completely customizable using CSS and XHTML.

Download

39. Create a Simple News Scroller Using MooTools


News scrollers are very common on internet because of their effectiveness. In this tutorial you will learn to create a simple news scroller using MooTools.

Read Full Tutorial
Demo

40. Checkbox Filtering Using MooTools ElementFilter

This tutorial will use MooTools ElementFilter to make a checkbox filter, for example if you are making a search box, when you type your search in the box, elements with matching text will automatically be checked!

Read Full Tutorial
Demo

This is all for this post. Anything missing or any suggestion? Do mention in your comments and we will be ha

June 15 2010

15:10

June 07 2010

14:30

May 27 2010

11:37

towel.js: momentum drag, simple code

Scato Eggen, in honor of Towel Day in the Netherlands, has released an open source framework called towel.js.

towel.js is an extension for Mootools, designed to make event-based code easier to write and even more important: easier to read.

At the hart of towel.js is a modular helper system called towel, including two helpers called UI and FX. These helpers produce objects that can be linked together: one object detects whether the mouse button is pressed, the other one changes style attributes. By linking these objects together a whole range of effects can be created and added to a page.

To create a simple momentum effect you only have to wire up code such as this:

JAVASCRIPT:
$ready().add(function() {
    var dragable = $('example-skid-dragable');

    var down = $towel(dragable).ui.down();
    var follow = $towel(dragable).fx.follow();
    var skid = $towel(dragable).phys.skid();

    down.add(follow);
    down.not().add(skid);
});
 

May 24 2010

18:15

April 29 2010

10:20

MooTools 1.3b1: A “Slick” release

The first beta of MooTools 1.3 has become available. The biggest feature is their new CSS selector engine. They aren't using Sizzle like some of the other boys, but instead have become Slick:

Slick is our new, shiny, super fast, exhaustively tested, pure-javascript selector engine. There will probably be a dedicated Slick post in the following days (or months, given our relaxed release cycles), but here’s a few Slick-facts for those who haven’t checked it out already:

  • Slick is a MooTools-family project by MooTools developers Thomas Aylott, Fabio Costa and yours truly. It can be forked from github, free of charge!
  • Slick is an incredibly advanced evolution of our previous selector engine.
  • Slick is written using only pure-javascript, none of the MooTools apis are required. It can be used in any project or framework, and it does not require MooTools to function (though the MooTools DOM components do require Slick).
  • Slick is speedy, blows away the 1.2 selector engine by 50%, at least. We will give you detailed data in the post dedicated to Slick.
  • Slick supports every selector you can think of. Seriously, every one of them. I promise you.
  • Slick is customizable, you can make your own pseudo-selectors, your own attribute-selectors, and many more your-own kinds of things.
  • Slick supports reversed combinators. You might not know what they are, but they are pretty darn cool.
  • Slick has a detached parser. You can parse a css-style-selector string and get back a property-filled object.
  • Slick perfectly supports XML documents.
  • Slick is slick!

This bleeds into some new APIs too.

For example, what you may have done like this:

JAVASCRIPT:
  1.  
  2. new Element("input", {"id": "someID", "class": "someClass1 someClass2", "disabled": true});
  3.  

you can now do using selectors:

JAVASCRIPT:
  1.  
  2. new Element("input#someID.someClass1.someClass2[disabled=true]");
  3.  

There are other features too:

Globals

MooTools 1.3 moves away from the $name functions. Most of the useless ones, such as $chk (god knows why I thought it was a good idea to have $chk), were completely nixed. Some of them moved to the proper object’s namespace ($merge » Object.merge, $pick » Array.prototype.pick). Some others were renamed without the stupid $ in front ($type » typeOf, $defined » nil). In the end, there are a lot less global variables now. You can refer to the 1.3 documentation to have a proper list of what’s changed. Keep in mind that the old version of the methods will still work, by default. There will be a way in the future to “compile” MooTools without the compatibility stuff, but the feature is not ready yet.

From types with love

Every native type has now a from method that will try to convert every object passed to that type. Array.from, for instance, replaces both $A and $splat. Function.from will return a function that returns the passed in value, if it wasn’t a function itself. String.from… well you know that at this point, don’t you? We also changed how we internally handle Native types, but that should be none of your concerns, since they were handled with private apis anyways.

Generating your own MooTools, from your own computer

It is now possible, easy, and even perhaps recommended to generate MooTools (and its plugins) yourself. Last few months I’ve been working, on and off, on a pretty advanced projects-builder. It’s called Packager, it supports multiple project dependancies and has a very similar syntax of what’s used in the Forge right now. It’s written in php and you can use it from your php webpages to dynamically include JavaScripts for development, or you can build a single .js for production from the command line.

March 24 2010

11:06

MooTouch: jQTouch has a Moo-y contender

Jacky Nguyen was behind a new website ExpatLiving from Singapore, and as he built out a nice view for iPhone and mobile Webkit folks, he implemented MooTouch. It is still in an early stage, and is asking for input:

MooTouch is a cutting-edge JavaScript framework built on top of MooTools that truly brings the experiences of iPhone / iPod Touch native applications to web applications. It is extremely lightweight and highly extensible, designed as a collection of loosely-coupled MooTools classes to handle all users’ touch interactions. Key features include:

MooTouch.App

  • Full Ajax experience, dynamic content loading on demand, ZERO page refresh or re-direction
  • Location hash handling
  • History management, makes full use of the browser’s back and forward buttons
  • Pages transition using Mobile Safari’s native CSS3 GPU acceleration
  • Automatic hiding of the browser’s location bar
  • Global event delegation to boost performance, and much more…

Some key behaviors that make the core of MooTouch:

  • MooTouch.Clickable: No more infamous 300ms delay before the “onClick” event is actually fired!
  • MooTouch.Scrollable: CSS position:fixed not possible on the iPhone? It was yesterday! Have full control over which content area you want to provide the simulated scrolling feature, with scroll indicators, deceleration & snapping back to boundaries features.
  • MooTouch.Swipeable: Bring “onSwipe” event to any DOM element you like, that’s how the photo gallery was done
  • and more to come…

MooTouch is different from most existing similar libraries thanks to the use-at-will architecture of MooTools. You can simply just pick the pieces you need and combine them the way you like. Also, you can use any existing interface framework like iUI, iWebKit, UiUIKit, etc. for styling and put MooTouch on top to control all users’ interactions with any DOM element.

MooTouch is currently still in alpha testing. It will be released under the Open Source MIT License as something I can give back to the great open-web community! All feedbacks are very much welcome.

March 04 2010

16:35

12 Steps to MooTools Mastery

This tutorial is about understanding and mastering the MooTools library. It does so by offering a high level introduction to the history and foundations of the Core library: where to start, where to explore, what to master, and more.

Tutorial Details

  • Program: MooTools
  • Version: 1.2.*
  • Difficulty: Intermediate
  • Estimated Completion Time: 1 hour

1: Prototypal Inheritance

step 1

The foundation of the MooTools framework is really in the prototypal inheritance model of JavaScript. In classical languages, like C++ or Java, a class represents something like a data type or what Jeff Mott called a “blueprint.” These blueprints are then used in the creation of objects. In fact, in these languages nothing is actually created until the “new” operator explicitly invokes them.

With JavaScript however, everything is created immediately, even before you instantiate the objects with the “new” operator. As a prototypal language, this effectively means no blueprints, no “classes”. Instead, we go about using some objects as fully operational bases for other objects. As Douglas Crawford said, in precisely this way JavaScript becomes “more capable and offers more expressive power.” Let’s take a look:

function Nerd(iq) {
    this.iq = iq;
    this.glasses = true;
    this.pants = 'high';
}

function SuperPowers() {
    this.strongerThanLocomotive = true;
    this.fasterThanBullet = true;
    this.canLeapBuildings = true;
}

Nerd.prototype = new SuperPowers();

Nerd.prototype.willWinGirl = function (hotness) {
    if(this.iq > (hotness * 20) || this.strongerThanLocomotive){
        console.log('maybe');
    }
    else {
        console.log('nope');
    }
}

new Nerd(140).willWinGirl(10); // logs "maybe"

The example above is actually a rather popular means of introducing the concept of prototyping. However, if you’re finding this a little too abstract, perhaps a better way to approach this would be to look at prototyping a native JavaScript constructor like String, Array, etc. For example:

Array.prototype.eachhhh = function (fn) {
    for (var i = 0, l = this.length; i < l; i++) fn(this[i]);
}

[0,1,2,3].eachhhh(function(item){
    console.log(item); // logs: 0,1,2,3
});

Prototyping simple code patterns like the for loop above can save tons of time when working on larger projects. When using the MooTools framework, it's important to begin thinking of every constructor as being extendable; this is going to save you time down the line and make your code much more flexible. Furthermore, it's precisely this method of inheritance that is at the core of MooTools, and harnessing this frameworks power means making use of prototyping. Of course, what MooTools does is make this process a whole lot easier for you to access and take advantage of, but we will get into exactly how it does this later on in the article.

2: Object Literal Notation

step 2

Wayyyy back in 2006, Chris Heilman was already getting fanatical about the object literal syntax... talking about sliced bread and other craziness. At any rate, for that very reason I'm not going to dwell on this subject too much, instead I'll assume that you've come across this syntax at some point or atleast can grasp it by the simple example below.

//this is not object literal notation
var variable1 = null;
var variable2 = false;

function1(){
// some code
}

function2(){
// some code
}

// the above becomes object literal notation below... 

var SomeVariableName = {

    variable1: null,
    variable2: false,

    init:function(){
    },

    function1:function(){
    // some code
    },

    function2:function(){
    // some code
    }
}

Like most programming languages, in JavaScript there exist a large number of stylistic preferences and "best practices." When working with MooTools you'll find there to be no shortage of these, including: not chaining excessively, capitalizing your class names, comma separating variable declarations, etc.... However, among these, object literal notation is perhaps most fundamental to understanding not only the way in which the MooTools framework itself is structured, but actually how to take advantage of this framework in developing your own code. We'll develop this idea further throughout the rest of this article and as you'll see, all the examples from this point forward will be taking advantage of this syntax.

3: The Class Constructor

step 3

If JavaScript doesn't have "classes," then why is there all this hype around Motools and classes? In May of last year, Aaron Newton published an excellent comparative piece on jQuery and MooTools. Among other things, he addressed precisely this question of classes in a very succinct way: "Despite its name, the MooTools Class function is not really a class nor does it create them. It has design patterns that might remind you of classes in a more traditional programming language, but really Class is all about objects and prototypal inheritance."
As Aaron goes on to detail, the MooTools framework is pushing for powerful and ultimately simple ways to organize and structure your code, ways which are elegant but also familiar, and not just semantically, but in their capacity to behave in classical design patterns. In fact, you'll find utilizing "classes" in your code base opens up your code to many powerful programming patterns: the mediator, the mixin, etc...

A simple MooTools class will look something like this (notice the syntax):

var YourClass = new Class({

    variable1: false,

    initialize: function(){
        this.toggleVariable();
    },

    toggleVariable: function(){
        this.variable1 = !variable1;
    }

});

var yourClassInstance = new YourClass();
yourClassInstance.toggleVariable(); // this.variable1 == false

Not too complicated, right? Once you begin structuring your code in classes like these, you'll find that your code repository will become not only a lot more organized and manageable, but actually smaller!

4: Class.Mutators

step 4

So how exactly does it become smaller? Returning to JavaScript's prototypal inheritance model and how it relates to the Class constructor, MooTools provides us with Extends and Implements. As properties, both are fundamental to the production of your MooTools subclasses and make this whole protyping mess a bit more intuitive. At a high level, Extends gives your subclass access to all the methods of it's base class, where methods and properties of the same name are overwritten (not to worry, they're still accessible through the parent() method). Similar to Extends, Implements adopts properties from one or more other classes, but without the inheritance model.

Consider briefly Digitarald's fancy upload plugin for Mootools. In this program Harald defines several classes, one of which is called the 'File' class. File houses the core functionality that a file object needs to interface with his uploading program and for this very reason is perfect for being extended; one might create an "Image File" subclass, a "Text File" subclass, etc. By modeling your code in this way, you are able to build your code up, rather than out. Consider the example below for how to use Extends:

var YourSubClass = new Class({

    Extends: YourClass, //here we are extending "YourClass" from our previous example

    variable2: false,

    initialize: function(){
        this.parent(); // this will call the initialize function from the bass Class "YourClass"
    },

    //here we are overwriting the toggle Variable function of "YourClass" with a new function
    toggleVariable: function(){
        this.variable1 = !variable1; // notice variable1 from "YourClass" is still accessible in YourSubClass
        this.variable2 = !this.variable1;
    }
});

5: Custom Events and Options

step 5

The most common usecase I find with Implements is including either the Events constructor or the Options constructor in my classes. As the name suggests, implementing Events allows for both the attachment and firing of custom events on your object, like onComplete, onFailure, onSuccess, onAnything. This level of abstraction becomes particularly useful when you begin sharing your code across several projects, where events behave as mediators between your current project and your plugins. In this way you can finally get away from those nasty one-to-one, bound relationships in your plugins. For example:

var YourSubClass = new Class({

    Implements: Events, //here we tell MooTools to implement Events in our sub class (this wont effect the bass "YourClass")

    Extends: YourClass,

    variable2: false,

    initialize: function(){
        this.parent();
    },

    toggleVariable: function(){
        this.variable1 = !variable1;
        this.variable2 = !this.variable1;
        //afterToggle() -- calling "afterToggle" would have made this function a necessary include of YourSubClass
        this.fireEvent('toggled'); //instead a custom event is fired called "toggled"
    }
});

var yourSubClassInstance = new YourSubClass();

var afterToggle = function(){
    alert('i\'ve just been toggled!');
};

//here we add a listener for the custom event, just like we would any other event
yourSubClassInstance.addEvent('toggled', afterToggle);

Besides Events, often you will want to Implement MooTools' Options. This utility class allows you to automate the setting of a list of optional properties to be set on an instance of your class. Again, this can be very helpful when writing plugins for various projects, allowing for the circumstantial customization of certain properties of your object. Consider the example below:

var YourSubClass = new Class({

    //One of the many cool things about the implements property is that it excepts an array.
    Implements: [Events,Options], //Here we include Options

    Extends: YourClass,

    //options are set if the invoker does not explicitly specify a value.
    options: {
        variable2: false
    },

    initialize: function(options){
        this.setOptions(options); //sets the options
        this.parent();
    },

    toggleVariable: function(){
        this.variable1 = !variable1;
        this.options.variable2 = !this.variable1;
        this.fireEvent('toggled');
    }
});

// this will start the class with variable2 = true.
var yourSubClassInstance = new YourSubClass({
    variable2: true
});

6: Binding

step 6

As your programs become more complex, a proper understanding of scope becomes invaluable. Scope is the way variables in JavaScript relate to any single point of execution -- there are global variables, which are variables that can be referenced from anywhere in the document and occupy the lowest executing level, local variables, which are variables limited to their immediate containing functions or closures, and finally, self references, the "this" keyword, which are JavaScript's way of referencing the context of the current point of execution.

var global = true; //global variable;

var aFunction = function(){
    var local = true; //local variable
}

$('button').addEvent('click', function(){
    this.addClass('clicked'); // self reference
});

When referencing a variable in your code, JavaScript bubbles from it's current executing position through all accessible levels of variables until it locates the first and nearest occurrence of a positive match. This behavior is often less than desirable, particularly when dealing with events inside of object literals as they house their own self references. Often developers rely on what are called "lexical closures" to circumvent problems like these, storing the self reference in a variable of a different name. However, MooTools provides an alternative means of achieving this through their bind() method, which is not only cleaner, but a lot more elegant. Consider the example below:

...

    addEvents: function(){
        $('button').addEvent('click', function(){
            //binding substitutes the current self reference for that of the object passed in
            this.toggleVariable();
        }.bind(this)); // here we bind this to the click event handler
    },

    toggleVariable: function(){
        //code
    },

...

7: The Element Constructor

step 7

In the example above we targeted an already existing element in the DOM and added an event listener to it. However, it's not uncommon today that you will see entire web apps load their content dynamically using JavaScript. With the evolution of JSON, being able to generate markup on the fly has become increasing necessary. Enter the MooTools Element constructor. The novel thing about this constructor is that it maintains it's readability despite it's large capacity for optional properties (Again, thanks to the object literal notation!). Element accepts an events object, a styles object, plus any individual properties like class, id, src, href, title, etc. That said, it's also loaded with a ton of methods, the complete list of which is available from the MooTools docs here. Below is a simple example of how to get started:

var el = new Element('div', {
    id: 'button',
    'html': 'hellloooo',
    styles: {
        display: 'block',
        position: 'relative',
        float: 'left
    },
    events: {
        click: function(){
            //your code
        }
    }
});

8: DOM Manipulation

step 8

Now that you have your dynamic element, wouldn't it be great to insert it into the DOM? MooTools provides a really handy list of methods for just that, including:

  • inject - places one element relative to the calling element : 'before', 'after', 'top', 'bottom'
  • grab - like inject but in reverse
  • adopt - works like grab accept it can accept an array of elements and you can't specify an exact relation
  • wraps - Works like grab, but instead of moving the grabbed element from its place, this method moves this Element around its target

Of these methods, I've found adopt's ability to accept an array of elements absolutely indispensable, especially when structuring larger quantities of dynamic markup. Consider the example below:

var el = new Element('div', {
    id: 'button',
    styles: {
        display: 'block',
        position: 'relative',
        float: 'left
    },
    events: {
        click: function(){
            //your code
        }
    }
}).adopt(

    this.createSpan(), // returns an element which can later be overwritten by a subclass

    new Element('a', {
        href: 'http://somewebsite.com'
    }).adopt(

        new Element('strong', {
            'html': 'world'
        })

    )
).inject($(document.body),'top');

The example above makes for a truly object oriented approach to DOM manipulation. When you become a super MooTools ninja, jedi, junky, nerd, you can use the method above to begin abstracting out functions which return elements or arrays of elements, making it possible for your subclasses to target specific methods in modifying your display. Awesome.

9: Request.JSON & Request.JSONP

step 9

JavaScript Object Notation or JSON is the lightweight data-interchange format that everyone loves (especially after working with XML). The great thing about JSON of course is that it's structure is recognized natively by JavaScript, and with many large sites opening up their data to the public via APIs, there's really no reason why you shouldn't invest the time to get familiar with it. No longer a cross browser nightmare, whether you're pushing data to a back-end service or requesting another batch of tweets from twitter, the MooTools Request constructor makes JSON and JSONP incredibly simple. It works with several event listeners and recently a timeout, which is completely neccessary once you start getting into JSONP. (Which you should! It's so fun.) Here's a simple example:

var JSONRequest = new Request.JSON({
    url: "http://yoursite.com/tellMeSomething.php",
    onFailure: function(){
        alert('oh nooo!');
    },
    onSuccess: function(response){
        alert('hooray!: ' + response.result);
    }
});

10: Fx

step 10

At a high level, the Fx constructor allows you to modify any CSS property of an HTML element, which itself accepts a single element and a series of optional properties (duration, transition type, etc.) to create smooth animation effects of colors, slides, scrolls, etc. What's more, the Fx constructor is fully compatible with Robert Penner's Easing equations, which are a great way to add a touch of uniqueness to your transitions like bounce, elastic, sin, etc.

If you're "hardcore" you can actually achieve all of the animation effects using either Fx.Tween(single css style animation) or Fx.Morph (multiple simultaneous style animations). Of course, beyond these there's Fx.Slide, Fx.Scroll, Fx.Accordian, etc. Here's a simple example using Fx.Tween:

var myFx = new Fx.Tween($('button'));
myFx.start('background-color', '#000', '#f00'); //this tweens the background color of the button element.

If you're dying to get deeper into this topic, check out Consider Open's fx tutorial for a fairly comprehensive introduction to the constructor.

11: Swiff

step 11

Originally appearing in Digitarald's fancy upload, the Swiff object allows your page's JavaScript to communicate with Flash. This makes it substantially easier to interact with Flash's unique functionality like video, sound, file streaming, and clipboard accessing features. More over, Swiff allows you to pass values and manipulate the Flash movie using conventions you're familiar with from JavaScript and Mootools. Integrating flash in this way is particularly useful as we begin taking steps towards offering HTML5 as a progressive enhancement, where, barring user's have the flash plugin, Swiff can be used to control audio or video on older browsers. Meanwhile, check out the simple example below:

var flashObject = new Swiff('sounds.swf', {
    id: 'mySoundManager',
    width: 1,
    height: 1,
    vars: {
        myVariable: true, //pass variables into flash on load
    },
    callBacks: {
        //call custom events from your flash object
        someEvent: function(){
            //code
        }
    }
});

Swiff.remote(flashObject, 'playMySound') //calls the function "playMySound" from within flash

12: Mootools More & Forge

step 12

Now with over fifteen members contributing to the official more plugin repository and over one hundred unofficial plugins already on Forge, it's no surprise that "Community" is what the MooTools team wanted us as developers to take away from 2009. Indeed people have truly embraced this framework, and now with Forge, we have a great place to meet each other and begin sharing ideas. You'll find David Walsh, Aaron Newton, 3n, and many others actively contributing amazing code and facilitating an environment capable of both inspiration and utility. In the end, the most helpful way to pick up the MooTools framework is by engaging with the developers around you and ultimately understanding what they are working on and how they're going about it.

Write a Plus Tutorial

Did you know that you can earn up to $600 for writing a PLUS tutorial and/or screencast for us? We're looking for in depth and well-written tutorials on HTML, CSS, PHP, and JavaScript. If you're of the ability, please contact Jeffrey at nettuts@tutsplus.com.

Please note that actual compensation will be dependent upon the quality of the final tutorial and screencast.

Write a PLUS tutorial


February 26 2010

11:25

ZooTool by MooTool(s)

Bastian Allgeier has developed a beautiful, native looking web application called ZooTool.

Zootool is a visual bookmark tool for images, videos, documents and links. It is completely based on Mootools, even though it looks more like a Cappuccino app!

Play with it. Enjoy it.

zootool

February 17 2010

17:45

Make your MooTools Code Shorter, Faster, and Stronger

MooTools is one of the most flexible, modular, and well written JavaScript frameworks available. So many people use it but many of them don’t optimize their code. This post will provide you with fifteen simple tips for making your MooTools code shorter, faster, and stronger.

1. Create Your Own MooTools Build or Pull From Google AJAX Libraries

One of the great advantages to using MooTools is that it’s incredibly modular. What does that mean?
Almost nothing is required unless you need it. The advantage of MooTools’ modularity is that your
limited, custom MooTools build can keep your JavaScript load time short.

MooTools Core Builder

Want to create a custom MooTools build for your next project? Follow these steps:

  • Go to http://mootools.net/core (and/or http://mootools.net/more if you’d like additional plugins)
  • Select the plugins of your choosing. Don’t worry about accounting for dependencies — the plugin builder does that for you!
  • Select the compression option of your choosing — the YUI Compressor will provide the you with the smallest possible build of MooTools

That’s it! Sometimes, however, your project requires the entire MooTools Core library. In that case, your website can save itself thousands
of requests per day by using the Google AJAX Libraries complete build of MooTools. You may do this two ways:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/mootools/1.2.4/mootools-yui-compressed.js"></script>

This first method simply includes MooTools into the page per normal. The second method allows more functionality and performance:

<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("mootools", "1.2.4"); //older versions also available
</script>

What’s great about using the Google AJAX Libraries API is that if another website uses the AJAX Library API, that version of MooTools is already cached
within their browser and the site will load faster!

2. Use jQuery and MooTools Together

While it’s best to stick to one library in a given page to avoid a bunch of overhead, sometimes you can’t avoid needing multiple frameworks.
Luckily MooTools can coexist with any non-prototype-based JavaScript frameworks. Here’s how you can use jQuery and MooTools in the same page:

<!-- jquery gets the "$" method -->
<script type="text/javascript" src="jquery-1.4.js" />
<!-- mootools doesn't steal the "$" method; instead, document.id will be used -->
<script type="text/javascript" src="mootools.js" />
<!-- lets use them -->
<script type="text/javascript">
//with jquery, grab all links, make then red
$('a').css('color','red');
//with mootools, get the content div, set it's background color to pink
document.id('content').setStyle('background','pink');
//with mootools, get the content div, set it's background color to pink
//this time, we'll give mootools the "$" method
(function($) {
	$('content').setStyle('background','pink');
})(document.id);
</script>

Thanks to MooTools’ Dollar Safe Mode, MooTools no longer assumes the “$” method if it’s already taken!

3. Save Elements and Element Collections

Developers often need to collect one element or a collection of elements. For example, you may need to grab all A elements within the page, change their color, and create tooltips from them.

//grab links, change color */
$$('#footer a').setStyle('color','#f00');
//make links tooltips
var tippers = new Tips($$('#footer a'));

The code above is grossly inefficient. Why query the DOM twice (with $$) if you can collect all of the elements once? Let’s make this more efficient:

//"save" links into a variable
var links = $$('#footer a');
//grab links, change color */
links.setStyle('color','#f00');
//make links tooltips
var tippers = new Tips(links);

You could make this even shorter, but it’s not as readable:

var tippers = new Tips($$('#footer a').setStyle('color','#f00'));

Readability is important, so I wouldn’t recommend coding this way if you work with a team.

4. Use Element Methods on Element Collections

Cycling through an array of elements is not unique to any JavaScript framework:

//for every link...
$$('a').each(function(a) {
	//add link nudging to the element
	a.addEvents({
		mouseenter: function() { //animate to the right
			if(!a.retrieve('oPad')) { a.store('oPad',a.getStyle('padding-left')); }
			a.tween('padding-left',30);
		},
		mouseleave: function() { //animate back to the left
			a.tween('padding-left',a.retrieve('oPad'));
		}
	});
});

What many developers aren’t aware that Element collections have the same methods as Elements,
so there’s no need to cycle through them — simply apply the desired functionality to the collection:

$$('a').addEvents({
	mouseenter: function() { //animate to the right
		if(!this.retrieve('oPad')) { this.store('oPad',this.getStyle('padding-left')); }
		this.tween('padding-left',30);
	},
	mouseleave: function() { //animate back to the left
		this.tween('padding-left',this.retrieve('oPad'));
	}
});

Note that the “this” keyword is used to reference the “current” element within the collection, not the collection itself.

5. Use MooTools Alias

MooTools’ “alias” method allows you to rename or alias an existing method. Take the following snippet of code which is currently in the MooTools Core source:

Array.alias('forEach', 'each');

The above code lets you call the “each” method instead of “forEach”. Using “each” is more readable, a quiet standard between most JavaScript frameworks, and
it even saves you a few bytes in your code. If you prefer to give MooTools’ Native or Class methods a custom name, feel free to!

For example, the Element Class’ method for removing an Element form the DOM is:

$('myElement').dispose();

Suppose your web app is about a given topic and you’d like to stay within that terminology for your code. Here are a few examples:

Element.alias('dispose','can'); //career site?
Element.alias('dispose','shank'); //prison site?

Whatever your reasons are for calling a method by a different name, just don’t be afraid to do so!

6. Create Custom Pseudo Selectors

Accessing a collection of Elements in the DOM is a core responsibility of any JavaScript framework. Unfortunately it can also be taxing and
the pseudo selectors you want aren’t always available. Luckily MooTools allows you to easily implement your own pseudo selectors! Let’s
create a pseudo selector named “disabled” that returns an element if it’s disabled.

//grab disabled elements
Selectors.Pseudo.disabled = function() {
	return this.disabled;
}

//how you use it
var disabledInputs = $$('input:disabled');

Simply add your selector to the Selectors.Pseudo object. If the new pseudo’s function returns “true”, the element is a match and will be returned.

Defining you own pseudo selectors is a great way to take control of your selectors!

7. Implement Methods on Existing Objects

MooTools’ philosophy is that it’s acceptable, even encouraged, to modify Native (String, Function, Number, etc.) prototypes when needed.
Implementing new methods on these Natives will empower them even more. Let’s create a String method that will turn any string of text into
“tweet” format (add links for @reply’s, links, etc.):

String.implement({
	toTweet: function() {
		 return this.replace(/(https?:\/\/\S+)/gi,'<a href="$1">$1</a>').replace(/(^|\s)@(\w+)/g,'$1<a href="http://twitter.com/$2">@$2</a>').replace(/(^|\s)#(\w+)/g,'$1<a href="http://search.twitter.com/search?q=%23$2">#$2</a>');
	}
});

Now you can call “toTweet” on any string and you’ll get the string back as a “tweet”. Here are a few examples:

//set an element's html to a tweet value
var el = $('myElement');
el.set('html',el.get('html').toTweet()); //sets the element's html to a linked, tweet value.

//alert the tweeted value
alert('Yo @NetTuts, check out my #MooTools website: http://davidwalsh.name'.toTweet());
//alerts:  Yo <a href="http://twitter.com/nettuts">@NetTuts</a>, check out my <a href="http://search.twitter.com/search?q=%23MooTools">MooTools</a> website: <a href="http://davidwalsh.name">http://davidwalsh.name</a>

Implementing custom methods on Objects strengthens every existing and future instance of that object.

8. Extend Existing Classes

MooTools’ OOP philosophy allows for a super-powerful inheritance model. Extending existing classes
allows you to avoid repeating code, empower existing objects, and leverage existing functionality.
MooTools Core, More, and your custom classes extend existing functionality. Consider the Request class:

var Request = new Class({

	Implements: [Chain, Events, Options],

	options: {/*
		onRequest: $empty,
		onComplete: $empty,
		onCancel: $empty,
		onSuccess: $empty,
		onFailure: $empty,
		onException: $empty,*/
		url: '',
		data: '',
		headers: {
			'X-Requested-With': 'XMLHttpRequest',
			'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
		},
		async: true,
		format: false,
		method: 'post',
		link: 'ignore',
		isSuccess: null,
		emulation: true,
		urlEncoded: true,
		encoding: 'utf-8',
		evalScripts: false,
		evalResponse: false,
		noCache: false
	},

	initialize: function(options){
		this.xhr = new Browser.Request();
		this.setOptions(options);
		this.options.isSuccess = this.options.isSuccess || this.isSuccess;
		this.headers = new Hash(this.options.headers);
	},

	onStateChange: function(){
		if (this.xhr.readyState != 4 || !this.running) return;
		this.running = false;
		this.status = 0;
		$try(function(){
			this.status = this.xhr.status;
		}.bind(this));
		this.xhr.onreadystatechange = $empty;
		if (this.options.isSuccess.call(this, this.status)){
			this.response = {text: this.xhr.responseText, xml: this.xhr.responseXML};
			this.success(this.response.text, this.response.xml);
		} else {
			this.response = {text: null, xml: null};
			this.failure();
		}
	},

	isSuccess: function(){
		return ((this.status >= 200) && (this.status < 300));
	},

	processScripts: function(text){
		if (this.options.evalResponse || (/(ecma|java)script/).test(this.getHeader('Content-type'))) return $exec(text);
		return text.stripScripts(this.options.evalScripts);
	},

	success: function(text, xml){
		this.onSuccess(this.processScripts(text), xml);
	},

	onSuccess: function(){
		this.fireEvent('complete', arguments).fireEvent('success', arguments).callChain();
	},

	failure: function(){
		this.onFailure();
	},

	onFailure: function(){
		this.fireEvent('complete').fireEvent('failure', this.xhr);
	},

	setHeader: function(name, value){
		this.headers.set(name, value);
		return this;
	},

	getHeader: function(name){
		return $try(function(){
			return this.xhr.getResponseHeader(name);
		}.bind(this));
	},

	check: function(){
		if (!this.running) return true;
		switch (this.options.link){
			case 'cancel': this.cancel(); return true;
			case 'chain': this.chain(this.caller.bind(this, arguments)); return false;
		}
		return false;
	},

	send: function(options){
		if (!this.check(options)) return this;
		this.running = true;

		var type = $type(options);
		if (type == 'string' || type == 'element') options = {data: options};

		var old = this.options;
		options = $extend({data: old.data, url: old.url, method: old.method}, options);
		var data = options.data, url = String(options.url), method = options.method.toLowerCase();

		switch ($type(data)){
			case 'element': data = document.id(data).toQueryString(); break;
			case 'object': case 'hash': data = Hash.toQueryString(data);
		}

		if (this.options.format){
			var format = 'format=' + this.options.format;
			data = (data) ? format + '&' + data : format;
		}

		if (this.options.emulation && !['get', 'post'].contains(method)){
			var _method = '_method=' + method;
			data = (data) ? _method + '&' + data : _method;
			method = 'post';
		}

		if (this.options.urlEncoded && method == 'post'){
			var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : '';
			this.headers.set('Content-type', 'application/x-www-form-urlencoded' + encoding);
		}

		if (this.options.noCache){
			var noCache = 'noCache=' + new Date().getTime();
			data = (data) ? noCache + '&' + data : noCache;
		}

		var trimPosition = url.lastIndexOf('/');
		if (trimPosition > -1 && (trimPosition = url.indexOf('#')) > -1) url = url.substr(0, trimPosition);

		if (data && method == 'get'){
			url = url + (url.contains('?') ? '&' : '?') + data;
			data = null;
		}

		this.xhr.open(method.toUpperCase(), url, this.options.async);

		this.xhr.onreadystatechange = this.onStateChange.bind(this);

		this.headers.each(function(value, key){
			try {
				this.xhr.setRequestHeader(key, value);
			} catch (e){
				this.fireEvent('exception', [key, value]);
			}
		}, this);

		this.fireEvent('request');
		this.xhr.send(data);
		if (!this.options.async) this.onStateChange();
		return this;
	},

	cancel: function(){
		if (!this.running) return this;
		this.running = false;
		this.xhr.abort();
		this.xhr.onreadystatechange = $empty;
		this.xhr = new Browser.Request();
		this.fireEvent('cancel');
		return this;
	}

});

Then consider Request.JSONP, which extends Request:

Request.JSON = new Class({

	Extends: Request,

	options: {
		secure: true
	},

	initialize: function(options){
		this.parent(options);
		this.headers.extend({'Accept': 'application/json', 'X-Request': 'JSON'});
	},

	success: function(text){
		this.response.json = JSON.decode(text, this.options.secure);
		this.onSuccess(this.response.json, text);
	}

});

You see how small the Request.JSONP class is? By adding “Extends: Request”, the Request.JSONP class gets all
of the Request Class’ methods. Essentially, this small snippet of code becomes a powerhouse because it extends
Request. You can even add extensions to extensions. Now consider Request.JSONP and then Scott Kyle’s Request.Twitter
class:

//Request.JSONP
/*
---

script: Request.JSONP.js

description: Defines Request.JSONP, a class for cross domain JavaScript via script injection.

license: MIT-style license

authors:
- Aaron Newton
- Guillermo Rauch

requires:
- core:1.2.4/Element
- core:1.2.4/Request
- /Log

provides: [Request.JSONP]

...
*/

Request.JSONP = new Class({

	Implements: [Chain, Events, Options, Log],

	options: {/*
		onRetry: $empty(intRetries),
		onRequest: $empty(scriptElement),
		onComplete: $empty(data),
		onSuccess: $empty(data),
		onCancel: $empty(),
		log: false,
		*/
		url: '',
		data: {},
		retries: 0,
		timeout: 0,
		link: 'ignore',
		callbackKey: 'callback',
		injectScript: document.head
	},

	initialize: function(options){
		this.setOptions(options);
		if (this.options.log) this.enableLog();
		this.running = false;
		this.requests = 0;
		this.triesRemaining = [];
	},

	check: function(){
		if (!this.running) return true;
		switch (this.options.link){
			case 'cancel': this.cancel(); return true;
			case 'chain': this.chain(this.caller.bind(this, arguments)); return false;
		}
		return false;
	},

	send: function(options){
		if (!$chk(arguments[1]) && !this.check(options)) return this;

		var type = $type(options),
				old = this.options,
				index = $chk(arguments[1]) ? arguments[1] : this.requests++;
		if (type == 'string' || type == 'element') options = {data: options};

		options = $extend({data: old.data, url: old.url}, options);

		if (!$chk(this.triesRemaining[index])) this.triesRemaining[index] = this.options.retries;
		var remaining = this.triesRemaining[index];

		(function(){
			var script = this.getScript(options);
			this.log('JSONP retrieving script with url: ' + script.get('src'));
			this.fireEvent('request', script);
			this.running = true;

			(function(){
				if (remaining){
					this.triesRemaining[index] = remaining - 1;
					if (script){
						script.destroy();
						this.send(options, index).fireEvent('retry', this.triesRemaining[index]);
					}
				} else if(script && this.options.timeout){
					script.destroy();
					this.cancel().fireEvent('failure');
				}
			}).delay(this.options.timeout, this);
		}).delay(Browser.Engine.trident ? 50 : 0, this);
		return this;
	},

	cancel: function(){
		if (!this.running) return this;
		this.running = false;
		this.fireEvent('cancel');
		return this;
	},

	getScript: function(options){
		var index = Request.JSONP.counter,
				data;
		Request.JSONP.counter++;

		switch ($type(options.data)){
			case 'element': data = document.id(options.data).toQueryString(); break;
			case 'object': case 'hash': data = Hash.toQueryString(options.data);
		}

		var src = options.url +
			 (options.url.test('\\?') ? '&' :'?') +
			 (options.callbackKey || this.options.callbackKey) +
			 '=Request.JSONP.request_map.request_'+ index +
			 (data ? '&' + data : '');
		if (src.length > 2083) this.log('JSONP '+ src +' will fail in Internet Explorer, which enforces a 2083 bytes length limit on URIs');

		var script = new Element('script', {type: 'text/javascript', src: src});
		Request.JSONP.request_map['request_' + index] = function(){ this.success(arguments, script); }.bind(this);
		return script.inject(this.options.injectScript);
	},

	success: function(args, script){
		if (script) script.destroy();
		this.running = false;
		this.log('JSONP successfully retrieved: ', args);
		this.fireEvent('complete', args).fireEvent('success', args).callChain();
	}

});

Request.JSONP.counter = 0;
Request.JSONP.request_map = {};

…and now Request.Twitter:

Request.Twitter = new Class({

	Extends: Request.JSONP,

	options: {
	  linkify: true,
	  url: 'http://twitter.com/statuses/user_timeline/{term}.json',
	  data: {
	    count: 5
	  }
	},

	initialize: function(term, options){
	  this.parent(options);
	  this.options.url = this.options.url.substitute({term: term});
	},

	success: function(data, script){
	  if (this.options.linkify) data.each(function(tweet){
	    tweet.text = this.linkify(tweet.text);
	  }, this);

	  // keep subsequent calls newer
	  if (data[0]) this.options.data.since_id = data[0].id;

	  this.parent(data, script);
	},

	linkify: function(text){
	  // modified from TwitterGitter by David Walsh (davidwalsh.name)
	  // courtesy of Jeremy Parrish (rrish.org)
	  return text.replace(/(https?:\/\/[\w\-:;?&=+.%#\/]+)/gi, '<a href="$1">$1</a>')
	             .replace(/(^|\W)@(\w+)/g, '$1<a href="http://twitter.com/$2">@$2</a>')
	             .replace(/(^|\W)#(\w+)/g, '$1#<a href="http://search.twitter.com/search?q=%23$2">$2</a>');
	}

});

You see how a waterfall effect of extending objects can make the smallest of classes an absolute beast of a class?
Experiment with MooTools’ inheritance model and don’t repeat code!

9. Create Custom Events

I’ve already explained how flexible the MooTools selector engine is, the class system is, and how modular the framework is.
Why would you expect anything different from MooTools’ event system? Creating custom events within MooTools is as simple
as it gets. Here’s a basic outline of your MooTools custom event:

Element.Events.altClick = {
	base: 'click', //the "base" event
	condition: function(event) {
		return event.alt; // alt key?
	},
	onAdd: function() {
		//do something when the event is added
	},
	onRemove: function() {
		//do something when the event is removed
	}
};

Here’s a great example of a custom event — listening for “alt” and “click” at the same time:

//alt click
Element.Events.altClick = {
	base: 'click',
	condition: function(event) {
		return event.alt; // alt key?
	}
};

//usage
$(document.body).addEvent('altClick',function() {
	alert('You alt-clicked me!');
});

Or you can simply define a custom event so that a specific function executes any time that type of event is assigned.
In my next example, any time a click event is assigned to an element, that element’s cursor will be automatically changed
to the “pointer” cursor.

/* update cursor on add/remove click event */
Element.Events.click = {
	base:'click',
	onAdd: function() {
		if(this.setStyle) {
			this.store('original-cursor',this.getStyle('cursor'));
			this.setStyle('cursor','pointer');
		}
	},
	onRemove: function() {
		if(this.setStyle) {
			this.setStyle('cursor',this.retrieve('original-cursor'));
		}
	}
};

You’ll notice that if the click event is removed, the original cursor will be restored.

10. jQuery-Style Events

While the MooTools event sytax is different from jQuery’s, it doesn’t have to be! With a minimal amount of
javascript you can make MooTools’ event syntax reflect jQuery’s.

MooTools holds all of its events in the Element.NativeElements object:

Element.NativeEvents = {
	click: 2, dblclick: 2, mouseup: 2, mousedown: 2, contextmenu: 2, //mouse buttons
	mousewheel: 2, DOMMouseScroll: 2, //mouse wheel
	mouseover: 2, mouseout: 2, mousemove: 2, selectstart: 2, selectend: 2, //mouse movement
	keydown: 2, keypress: 2, keyup: 2, //keyboard
	focus: 2, blur: 2, change: 2, reset: 2, select: 2, submit: 2, //form elements
	load: 1, unload: 1, beforeunload: 2, resize: 1, move: 1, DOMContentLoaded: 1, readystatechange: 1, //window
	error: 1, abort: 1, scroll: 1 //misc
};

Essentially all you need to do is cycle through each element type and implement a method on the Element class, named like the event type,
that simulates what addEvent does:

//hash the element.natives so you can do stuff with it
var hash = new Hash(Element.NativeEvents);
//remove items that need to be replaced, add their replacements
hash.erase('mouseover').erase('mouseout').erase('DOMMouseScroll');
hash.include('mouseenter',1).include('mouseleave',1);
//initialize this
var eventHash = new Hash({});
//for every event type, add to the hash
hash.getKeys().each(function(event){
	eventHash[event] = function(fn) {
		this.addEvent(event,fn);
		return this;
	};
});
//make it happen
Element.implement(eventHash);

Now you can listen for events like:

$('myElement').click(function() {
	//do stuff
});

11. Add Events During Element Creation

If you have experience coding with MooTools, at some point you’ve no doubt created an element and subsequently added events to it:

var myElement = new Element('a',{
	href: 'mypage.php',
	text: 'Click here!'
});

myElement.addEvent('click',function(e) {
	//stop the event
	if(e) e.stop();
	//do stuff
});

There’s nothing wrong with the above, per say, but you could just add those events during element creation:

var myElement = new Element('a',{
	href: 'mypage.php',
	text: 'Click here!',
	events: {
		click: function() {
			//stop the event
			if(e) e.stop();
			//do stuff
		}
	}
});

12. Implement Events Within Classes

Extending classes was discussed in tip #8 above. Now lets explore the *implement* functionality within MooTools classes.
What’s the difference? MooTools contributor Mark Obcena says it best in his article titled
Up The Moo Herd IV: There’s A Class For This:

MooTools has two built-in mutators: Extends and Implements. The Extends mutator takes the class name passed on to it and makes the new class inherit directly from it, while Implements takes the class (or classes) passed and adds their methods to the new class (or mixes them in—thus mixin).

With the difference between extending and implementing, lets get back to it. Implementing events within your MooTools classes
can make your classes much more flexible. Consider the following simple Overlay class:

var Overlay = new Class({

	Implements: [Options,Events],

	options:  {
		id: 'overlay',
		color: '#000',
		duration: 500,
		opacity: 0.5,
		zIndex: 5000
	},

	initialize: function(container,options) {
		this.setOptions(options);
		this.container = document.id(container);
		this.overlay = new Element('div',{
			id: this.options.id,
			opacity: 0,
			styles: {
				position: 'absolute',
				background: this.options.color,
				left: 0,
				top: 0,
				'z-index': this.options.zIndex
			},
		}).inject(this.container);
		this.tween = new Fx.Tween(this.overlay,{
			duration: this.options.duration,
			link: 'cancel',
			property: 'opacity',
			onStart: function() {
				this.overlay.setStyles({
					width: '100%',
					height: this.container.getScrollSize().y
				});
			}.bind(this)
		});
	},
	open: function() {
		this.tween.start(this.options.opacity);
		return this;
	},
	close: function() {
		this.tween.start(0);
		return this;
	}
});

Sure the class does what it’s supposed to but it isn’t nearly as flexible it could be. Now lets implement
onClick, onClose, onHide, onOpen, and onShow events:

var Overlay = new Class({

	Implements: [Options,Events],  // EVENTS IMPLEMENTED HERE!

	options:  {
		id: 'overlay',
		color: '#000',
		duration: 500,
		opacity: 0.5,
		zIndex: 5000/*,
		onClick: $empty,
		onClose: $empty,
		onHide: $empty,
		onOpen: $empty,
		onShow: $empty
		*/
	},

	initialize: function(container,options) {
		this.setOptions(options);
		this.container = document.id(container);
		this.overlay = new Element('div',{
			id: this.options.id,
			opacity: 0,
			styles: {
				position: 'absolute',
				background: this.options.color,
				left: 0,
				top: 0,
				'z-index': this.options.zIndex
			},
			events: {
				click: function() {    // CLICK EVENT
					this.fireEvent('click');
				}.bind(this)
			}
		}).inject(this.container);
		this.tween = new Fx.Tween(this.overlay,{
			duration: this.options.duration,
			link: 'cancel',
			property: 'opacity',
			onStart: function() {
				this.overlay.setStyles({
					width: '100%',
					height: this.container.getScrollSize().y
				});
			}.bind(this),
			onComplete: function() {
				this.fireEvent(this.overlay.get('opacity') == this.options.opacity ? 'show' : 'hide');  // SHOW OR HIDE EVENT
			}.bind(this)
		});
	},
	open: function() {
		this.fireEvent('open');  // OPEN EVENT
		this.tween.start(this.options.opacity);
		return this;
	},
	close: function() {
		this.fireEvent('close');  // CLOSE EVENT
		this.tween.start(0);
		return this;
	}
});

What’s great about adding events to a class is that events allow your to give more options and trigger functionality when
our class methods execute. In the above example, you can execute any functionality when the overlay opens, closes, shows, hides, or gets clicked.
Essentially you added two tiny snippets of code to the class:

Implements: [Events]

…and the following wherever you’d like an event to be signaled…

this.fireEvent('someEvent',[argument1, argument2]);

So how can you control these events when you create an instance of the class? Add them in the options like this:

var overlay = new Overlay({
	onClick: function() {
		this.hide();
	},
	onOpen: function() {
		alert('Thank you for opening!');
	}
});

You’d be hard pressed to find a class that wouldn’t benefit from implementing events!

13. Use Event Delegation

Event delegation is the process of adding an event to a parent for all of its children instead of assigning the
event to each individual child. The advantage of event delegation is that you may add child elements to the
parent element without needing to assign the event to that new element. If you choose to remove the event,
you need only remove it from one element.

So, instead of:

$$('a').addEvent('click',function() {
	//do stuff -- individually assigned
});

…you do this:

$('myContainer').addEvent('click:relay(a)',function() {
	//assigned to the parent of all A elements (in this case, #myContainer), to listen to A element click event
})/

Don’t let the “:relay()” pseudo-syntax fool you; Element.Delegation rewrites the event methods to accommodate for :relay.

14. Use Class.toElement

One hidden gem within MooTools’ Class is the Class.toElement method. Class.toElement plays a small role but can help you out
when it comes to accessing the primary element within a class, especially if you don’t know what that element is otherwise.
Implementing toElement on your class is easy:

var myClass = new Class({

	Implements: [Options],

	initialize: function(container,options) {
		this.container = $(container);
	},

	toElement: function() {
		return this.container;
	}
});

Once you have toElement defined, you can use your class just like an element:

var myInstance = new MyClass('myElement');
myInstance.setStyle('color','#f00').set('html','This is my element!');

Look at that — a class virtually manipulated by Element methods.

15. “return this” Within Methods For Chainability

So we’ve all seen how the JavaScript frameworks allow you to chain the hell out of methods. Chaining looks like this:

$('myElement').setStyles('color','#f00').set('html','Click Here').fade('out').addClass('cssClass').addEvent('click',function(e) {
	if(e) e.stop();
	alert('Clicked'!);
});

Holy chaining Batman! Want your classes to chain forever? No problem — all you need to do is return “this”:

var myClass = new Class({

	//options, initialize, implements, etc.

	doSomething: function() {
		//do a whole bunch of functionality here and...
		return this;
	},
	doAnotherThing: function() {
		//do a whole bunch of functionality here and...
		return this;
	},
	doYetAnotherThing: function() {
		//do a whole bunch of functionality here and...
		return this.
	}
});

Since you placed “return this” in each method, now you can do:

var klass = new myClass();
klass.doSomething().doAnotherThing().doYetAnotherThing();

Make sure to return “this” wherever it makes sense. Doing so can make your Class much easier to work with and your code will be shorter!

BONUS! 16. Use Fx Shortcuts on Elements

MooTools effects are unarguably the smoothest of any JavaScript framework. The Fx library also provides loads of control through numerous options.
Lets take a look at a basic Tween which fades an element to 50%:

var myTween = new Fx.Tween('myElement',{
	duration: 500,
	fps: 200,
	//a bunch of options here
});
//fade to 50%
$('myElement').addEvent('click',function() {
	myTween.start('opacity',0.5);
});

Did you know you didn’t need to type out all of this? You could use element shortcuts like:

$('myElement').fade(0.5); //fading: Fx.Tween
$('myElement').tween('width',300); //tweening: Fx.Tween
$('myElement').morph({
	width: 200,
	height: 300
}); //morph:  Fx.Morph

The above snippets, of course, rely on you wanting to use the default options. You can actually set custom options for these shortcut methods per element:

$('myElement').set('tween',{ duration:500, fps: 200 }).tween('width',300);

Save your self a few bytes by using Fx shortcuts!

MooTools FTW!

Hopefully I’ve given you some tips to improve your MooTools JavaScript code, making it shorter, faster, and stronger. Have some of your own tips to share?
Place them in the comments below!


Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.
(PRO)
No Soup for you

Don't be the product, buy the product!

close
YES, I want to SOUP ●UP for ...