Articles in the ‘All’ Category

Setting Up Elements

Written By , on Thursday, June 10th 2010, 11:16pm

Once you know how much easier it is to get elements all around, you should take the time to learn how MooTools has provided a simple access API around the browser quirks for Elements. And on top of it, we’ve extended this API to things that you don’t normally find on Elements. And as cool as it is, you can easily add your own bits with ease.

Get Who? Set What?

On Elements, theres only 3 getters/setters that you need to worry yourself with: get/set, getStyle/setStyle, and store/retrieve (we’ll ignore getProperty for now).

Get/Set

The most commonly used are Element#get and Element#set. They will first check the Element.Properties object to see if a specific getter/setter exists, before defaulting to getProperty or setProperty. So for instance, you can get the href of a link, or you can get the text of an element, which will get the node value in a cross browser fashion.

<a id="myAnchor" href="/blog">Blog</a>
<div>All my <span>text</span></div>

$('myAnchor').get('href'); // '/blog'
$('myDiv').get('text'); // 'All my text'

You can do as you would expect with the setters in the same way.

$('myAnchor').set('title', 'MooTools Blog'); //sets title attribute
$('myDiv').set('text', 'other text'); //sets the innerHTML

For now, let’s just look at the other methods, and we’ll take a look at how this works later so you can add to it yourself.

Setting with Style

The other commonly used pair of methods are Element#getStyle and Element#setStyle. These should hopefully be self explanatory. Their benefit is that they normalize certain styles the browsers are inconsistent about, such as opacity.

Elemental Properties

Let’s take a look at an example that MooTools itself defines. The style property is easier to remember and read than using cssText, so that’s what MooTools does for us.

Element.Properties.style = {

    set: function(style){
        this.style.cssText = style;
    },

    get: function(){
        return this.style.cssText;
    }

};

Seeing how the style object is setup, you can easily create your own. Given a Person class, and the given HTML, we could decide it would beneficial to be able to get the instance of a Person from an element.

<div class="person person_3">
    Sean
</div>
<p>Hello</p>

Say we were to want to get a Person instance when we have this element. We would define the property on Element.Properties.

Element.Properties.person = {

    get: function() {
        var id = this.className.match(/person_(\d+)/)[1];
        if(id) return Person.getById(id);
    },

    set: function(person) {
        this
            .addClass('person')
            .addClass('person_'+person.id)
            .set('html', person.name);
    }
};

Now we can use our familiar get and set methods.

$('TestPerson').get('person'); // returns Person instance of ID 3.
$('OtherTest').set('person', new Person('John')); //turns the paragraph into a person
// <p class="person person_4">John</p>

Let’s just Store that

The third pair of methods that MooTools defines for elements is Element#store and Element#retrieve. Woah woah woah. What? You’re telling me you can get properties, and you can retrieve them? What the heck guys?

Don’t worry, it’s pretty easy to know and understand the difference once I explain it. get and set are the most common methods, and default to element attributes, like I said. In many other places, such as when you use el.get('tween'), the MooTools teams made the getter call retrieve for you. You’ve been accessing it, without knowing it.

OK, great Sean. Why should I care how you give me the values?

I hear you. You see, most of the getters/setters are used to access attributes. But what happens you want to get at or set some other kind of property. What if you want to set an actual object, or a function to the Element. I guess you could JSON encode and create a custom attribute, but that’s not good practice. And you lose out on any class info of the object, in case it was an instance of something.

These methods also help with an issue that arises when you try to store something like an Event object or an instance of something else that refers to the Element in question. Certain browsers don’t handle the circular references that well if you were to set el.prop = { someEl: el }. It can leave nasty memory leaks.

If you really want to know, behind the scenes, MooTools keeps a storage object that is totally separate from any element. Every element created gets assigned a unique id, and that id is used as a key on the storage object.

Regardless, you don’t have to do anything special for store/retrieve to work. Using our above example, it would work like so:

$('TestPerson').store('person', new Person('Sean'));
$('TestPerson').retrieve('person'); //returns the exact same Person instance

These two common pairs of methods actually have a third method that relates to each of them, which allows the destruction of each respective data location. These methods are Element#erase and Element#eliminate.

Apply this yourself

This all sounds great, I’m sure. Now when you’re writing your own classes and plugins, you can be sure to use the pre-packaged properties. However, it’s much more powerful when you can find a useful property to add that relates to your own plugins.

Sean McArthur is a software developer at Blazonco.com who is madly in love with MooTools. Most of his contributions involve sharing tips and information about MooTools (and programming in general) at his blog and on Twitter.

MooTools Core 1.3 beta 2

Written By Christoph Pojer, on Thursday, June 3rd 2010, 10:46pm

Over the past couple of weeks we have got a lot of great responses over the initial beta of MooTools Core 1.3. We have since improved both the code and the documentation in order to release a second beta.

Most notably we have removed the dependency on Hash. If you build 1.3 without compatibility you won’t get the Hash object no more. But fear not, we have added Object.js which brings you all the Hash methods as generics. Everything else is really minor, has to do with stability or was meant to improve code quality (we really take this seriously).

We are trying hard to provide you with a consistent and meaningful API so we have decided to introduce one tiny tweeny minor breaking change. If you were setting tween, morph, load, or send options using the getter (element.get('tween', {...options here...})) that will not work anymore. You will have to use set(element.set('tween', {...options here...})), as get needs to be a pure getter.

All in all the new beta is faster, better, more stable - in a word - sexier. Tell us how it works for you.

Download

Thanks to everyone who helped polishing the 1.3 release. I would really like to thank Arian Stolwijk (@astolwijk) who has contributed significant improvements to the documentation.

A Magical Journey into the Base Fx Class

Written By , on Tuesday, May 18th 2010, 11:46am

Fx is not just for animating elements

In a recent project I worked on with Thomas Aylott the page did some calculations and displayed the result after the user pulled some sliders around. Rather than just change the text from one number to another, the element would increment the number before the user’s very eyes. With a fun interface like that, they had no choice but to apply for a new credit card right then.

Admittedly, I may not have thought to extend Fx to do something like that. After all, the first line of the docs for Fx is: “This Class will rarely be used on its own, …” My first thought would be to use a periodical with a counter and then set the text until the counter was done. But Thomas extended Fx instead. Though it’s the base class for all animations (tween, morph, scroller, etc.) its methods can be used for all sorts of abstract “animations.”

For this article I’ve just come up with a few potentially useful extensions of Fx to get the idea across that you can use it for more than just element animations.

How Fx Works

Essentially Fx just calculates a sequence of values between two numbers. The options kick in to make those values more interesting. This class, Fx.Log, simply updates the text of an element every step of the effect. Notice that this class is essentially the base Fx class except for the tiny set method.

Here’s another demo that visualizes all the visible options of Fx. After you draw the effect, hover the dots to see the exact value calculated (or view source and see them all together.) Playing around with this demo might tell you more about how Fx works than anything else out there.

Fx.Diff

By default, Fx uses 50 fps. So every second it’ll kick out 50 different values and fire the set method 50 different times. For the next few demos I only wanted to do something if the rounded value is different than the last rounded value, so I came up with Fx.Diff. If the value is different, it’ll call the render method.

Fx.Diff = new Class({

    Extends: Fx,
    count: 0,
    render: $empty,

    set: function(now){
        now = now.round();
        var diff = now - this.count;
        if (diff) {
            this.render(diff, now);
            this.count += diff;
        }
        return this;
    }

});

Fx.Count

Since this appears to be no different than the very first demo, we’ll just look at the code. Note, the difference is that the first counting demo would change the text in the element every single frame (50 times a second), but this code would only change it if the new rounded value is different from the last.

Fx.Count = new Class({

    Extends: Fx.Diff,

    initialize: function(element, options){
        this.element = document.id(element);
        this.parent(options);
    },

    render: function(){
        this.element.set('text', this.count);
        return this;
    }

});

Fx.Typewriter

I can actually see myself using this one somewhere:

Notice that Fx.Typewriter overwrites the start method of Fx. The Fx start method takes two arguments, from and to. The usage for Fx.Typewriter is to simply pass in a string of text like so: myFx.start('A whole bunch of text'). This new method knows the from argument is always 0, splits up the text into an array (one item per character) and then uses that length as the to argument. After that logic is done, it simply calls the parent start method. Then the render method takes over by figuring out how many characters to display, filtering out the tail end of the array, joining what matters, and finally setting the text of our element.

Fx.Text

There’s a very creative effect called Fx.Text on the forge. It’s an animated text replacement effect. I think it’s really cool and does a great job of extending Fx.

Fx.Cornify

This next script is far too magical to simply show you the code. You’ll need to view the source for this beauty.

How many? (caution, start with low numbers)

Duration:

Ryan Florence is a MooTools enthusiast and contributor. He maintains his JavaScript focused blog, MooDocs.net, and moo4q. Follow him on twitter or checkout his plugins on the Forge.

Announcing: MooTools in Real Life

Written By Michelle Steigerwalt, on Wednesday, May 5th 2010, 12:52pm

If you’ve been paying attention for the past few years, you’ve probably noticed the growth of MooTools, both as a project and as a thriving community. Unfortunately, it has come to light that many so called “members” of the JavaScript community may, in fact, be automata.

To protect ourselves and the MooTools community, we’ve started two physical screening programs (or “meetups”), one in London and the other in the heart of Silicon Valley.

In a surprising turn of events, both groups have had very informative meetings in which actual people have shown up, allowing us to conclusively state that at least some of the members of the MooTools community are, in fact, human. Insightful discussions were had by all, new users and advanced developers alike.

If you’re in the Bay Area or London, it is imperative that you attend at least one of our screening sessions, to verify yourself as human. To be notified about future meetups, as well as voice your opinion on when/where they should be, you can join the Meetup.com group for your area:

Anything Interesting to Share?

If you have something insightful and MooTools-related to share, and think you can spin it into a fifteen minute presentation, please let us know.

Right now, we don’t have any formal communication set up, but it shouldn’t be to hard to get in touch with either Darren (London) or myself (Bay Area). Contact information can be found on the developers page.

Thanks for using MooTools, and we hope to see you there!

MooTools 1.3 ßeta 1

Written By Valerio Proietti, on Tuesday, April 27th 2010, 6:25pm

MooTools 1.3 beta 1 launches today. Lots of bug fixes and improvements, and all that jazz. Before presenting you with a random rundown of features, let me be clear about something: MooTools 1.3 is (or will be) 100% compatible with every public documented API of MooTools 1.2. So chill already.

Anyways, here’s what’s new:

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.

If you care to build MooTools and MooTools projects for yourself, you should take these steps:

  1. Clone MooTools 1.3b1.1 from github.
  2. Clone whatever other Packager-ready MooTools project from github (color, table and touch, for instance, are my Packager-ready plugins).
  3. Clone Packager itself from github.
  4. Read Packager’s README. Pretty much everything you need to know is in there.

Ofcourse, Packager itself is not limited to MooTools, MooTools plugins or just javascript projects. A tutorial post on how to use Packager for development is coming soon (few years tops).

If you dislike php, worry not! There is also a Django builder, called Depender, written by our Aaron Newton, on github as well. I really don’t know how it works, as I don’t do python, but I do know it’s scope is way greater than that of Packager. Depender can, for instance, dynamically build your MooTools for production use, like that. But don’t take my word for it, go check it out on github.

Slick

The most notable new feature in 1.3 is 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!

On another note, thanks to the Slick’s parser, you will be able to build an element using a css selector. Let me give you an example of this cool new feature (courtesy of our amazing Christoph Pojer):

Creating an element using an object (the 1.2 way):

new Element("input", {"id": "someID", "class": "someClass1 someClass2", "disabled": true});

Creating an element using a selector string (the coolest way):

new Element("input#someID.someClass1.someClass2[disabled=true]");

In conclusion

As I get back to work on an exciting number of totally amazing upcoming MooTools projects that you know nothing about because you don’t follow me on github, I’ll leave you with a few useful 1.3 links:

UPDATE: There was a “merge” problem with beta1, so we quickly fixed it and re-tagged beta 1.1.

Have fun with 1.3! I know I will.

Valerio