Follow me: @D_mitar

Most read posts recently



Mar 12th 2011 × Tutorial: write a small but flexible MooTools Tips class

The other day somebody came in on the IRC channel and asked if there’s a MooTools script available to replicate the effect of this jQuery plugin.

The main objective was to be also easily able to keep the tip on whilst the mouse skips from the trigger element into it. Since I did not know off the top of my head of an adequate MooTools class to perform the task, I simply took 30 mins to write one. This is to document that and explain the decisions behind it.

To get an idea what our class will do when done, view http://jsfiddle.net/dimitar/WUfNR/show/ or look at the source code on git.

As a disclaimer: this is NOT a port of the jQuery plugin mentioned. I have not looked at the source code and simply am replicating the effect and using their graphics for convenience’ sake.

Also, this mini-tutorial or (even code-review) is aimed at people who already have rudimentary knowledge of Javascript, MooTools, CSS, DOM and understand the concept of classic OOP. Recommended read on how MooTools deals with OOP and the Class constructor in general is Keeto’s Up The Moo Herd III article.

First: decisions, decisions. Planning ahead is important so… The easiest way to achieve the effect we are after without firing onmouseout when moving the mouse into the ‘tip’ is to have the tip become a child element of the trigger element. To understand that better, consider it as a simple HTML/CSS markup solution where a child div has absolute positioning and some negative marginTop. Although this is very easy, it is a somewhat limiting decision as it means the tip element can only be injected into the DOM with a parentNode that can have children. input, img, textarea are not good for us to attach to directly. It’s not that much of a drama as you can wrap them into spans or divs, which will work fine.

The start: creating the MooTools class skeleton

this.tippable = new Class({

    Implements: [Options, Events],

    options: {
        tipClass: ".tippable",
    },

    initialize: function(element, options) {
        // public instantiation

        this.setOptions(options);
        this.element = document.id(element);
        if (!this.element)
            return;
    }

});

What is happening here? Basically we are defining a new MooTools Class called ‘tippable’. Within that class we use the MooTools Options and Events classes as mixins. The Options class is useful for merging options from the instance that override the default class options property by doing an `Object.merge(options, this.options);`. This functionality is available through the `this.setOptions(options)` call and is a great practice that allows you to setup defaults that can be changed by the instance. The Events mixin is another very handy Class that brings Events (surprise) into your classes and can be used in conjunction with options object you pass on. The premise is simple: whenever something ‘awesome’ happens in your class that the instance should know about, you can do `this.fireEvent(“awesome”, [params])` and if on your options object on your class instance you have a property `onAwesome: function() { … }`, it will get passed with the scope of the class itself. More on this later.

Maintaining your MooTools Classes requires you to adhere to some unwritten rules that make it easier for developers to follow what’s going on. From that point of view, it’s an accepted convention that if your class deals with a particular element, it should be referenced as `this.element`. An array of elements would be… `this.elements` and so forth (hint: read the linked article above).

We are also making sure that an element has been passed and it’s a DOM node, something that the `document.id()` call ensures. It’s unsafe for the Class to continue if it can’t find the element so it exits quietly. You may want to trigger an exception here or degrade gracefully – depends on your requirements.

Building your Class

It’s now time to add our first ‘real’ method. I like to break the Class down into multiple small methods that are self explanatory and do as little as possible. This is a great practice for many reasons: it means your code is self explanatory and reduces the need for leaving comments. It also allows you to create patterns that you can call again and again. We are going to create a new method we are going to call `attachTip`

attachTip: function() {
    // call creation and events addition
    this.createTip();
    this.attachEvents();
},

As you can see, it will call two more methods we will add: one that creates the tip into the DOM and one that deals with the trigger events.

I am going to post the finished version of the method and it will reveal references to options and methods we have not mentioned yet. Basically – as a practice, I tend to add to my default options object as I see fit whilst I am writing the code and come to a decision about using a static value or a variable that may be useful for the user to override.

createTip: function() {
    // add tip to dom and set initials

    // first event will be onShow
    this.event = "show";
    this.tip = new Element(this.options.tipClass, {
        styles: {
            opacity: 0
        }
    }).set("morph", Object.merge(this.options.fx, {
        onComplete: function() {
            this.fireEvent(this.event);
        }.bind(this)
    }));

    // store title
    this.title = new Element("div.title").inject(this.tip);

    // tip body
    this.body = new Element("div.body").inject(this.tip);

    // append to DOM
    this.tip.inject(this.element, "top");

    // store instance into the tip element for event use!
    this.element.store("tippable", this);

    // set initial title and body values
    this.setTitle(this.options.title);
    this.setHTML(this.options.text);

    // now to position element
    if (this.options.leftOffset === false) {
        var tipWidth = this.tip.getSize().x, elWidth = this.element.getSize().x;
        this.tip.setStyle("marginLeft", (elWidth - tipWidth) / 2);
    }
    else {
        this.tip.setStyle("marginLeft", this.options.leftOffset);
    }

}, // end createTip

As I just pasted this, it occurred to me it would be useful to allow users to define their own CSS ClassNames for the tip title and tip body, even if they can be targeted in CSS as `value-of-this.options.tipClass div.title {..}`. Anyway, that’s a change you can quickly do. Similarly, we are going to be using certain variables passed through options or defaults. The default options for the Class now look like this:

options: {
    // NB: these are zen classes for Slick
    tipClass: "div.tippable",
    text: "",
    textClass: "div.body",
    title: "",
    titleClass: "div.title",
    topOffset: 110, // where it stops above the element
    topOffsetStart: 160, // where the animation starts from.
    leftOffset: false, // if false, center over element, else, integer
    // Fx class options
    fx: {
        duration: 400,
        link: "cancel"
    }
},

To reiterate: if you do not pass an options object to the Class instantiation, it will still work with the default values. If you want to override a single option, you do that and the rest are defaults. The key / interesting options we use are these:

  • tipClass, textClass: a ‘zen-coding like’ element hook to create and style the tip container (by ID or CSS reference). In MooTools 1.3, Slick can work with Element in reverse, you can even declare things like `new Element(“div#someid.foo[html=hi]“);`
  • fx: an object that provides the ability to pass on options to the Fx.Morph instance on the tip element such as duration, Fx.transition and so forth.
  • topOffset and topOffsetStart: can control the ‘animation’ path – where to start from and how far above (or below) the element to stop. By using negative values here, you can do a tip that flies from bottom to top instead…
  • leftOffset: that value I added later when I realised I may not always want to try and center the tip above the trigger element but may want to output it to the left at nn pixels. if False, centered, else, marginLeft becomes leftOffset instead.
  • text / title: Last but not least, the default text body and title for the tip.

Back to the function. In a nutshell, when attaching the tip to the DOM, it makes a new div, say div.tippable (styled through CSS alone) and makes it invisible by default. It also defines the Fx morphing options and helps out a little with the events it will fire onShow and onHide. I will go in more details over why events are important and how you can use them in the instance.

The tip is injected – as stated before – as a child node of the trigger element – so it needs to be styled via CSS to have position: absolute.

An interesting thing that I do here is I also store the tip instance into the trigger element storage (via this.element.store(“tippable”, this);). This allows me to programatically control the tip instance from external javascript by simply having access to the element where I can get the instance by `var instance = doing elObj.retrieve(“tippable”);`. It’s great so that I don’t have to store each instance into a separate variable into my scope in case I want to remove it, modify it or show a tip without mouse events.

Another interesting thing is I have added public methods which allow for the changing of the tip title and body via setTitle and setHTML. This means you can control the content and change it dynamically or even bring in tip content through events and ajax, which I will show later on. Back to the Class, we are adding these two simple methods:

setTitle: function(what) {
    // set the title content public api
    if (what.length) {
        this.title.set("html", what);
    }
    return this;
},

setHTML: function(what) {
    // set body content public api
    this.body.set("html", what);
    return this;
},

Please note the return this; at the end of some of the methods. This is another unwritten rule in the MooTools world: allow for chaining. By having the Class instance as the exit/return point of a method, it allows you to chain more methods to it. In other words, you can do on a single line:

this.setTitle("hello").setHTML("this be the tip text, ahoy!");

When dealing with DOM events pointing back to your class methods, things are slightly trickier at first:

attachEvents: function() {
    // private
    this.boundEvents = {
        mouseenter: this.showTip.bind(this),
        mouseleave: this.hideTip.bind(this)
    };
    this.element.addEvents(this.boundEvents);
    return this;
},

detatchEvents: function() {
    this.element.removeEvents(this.boundEvents);
    return this;
},

What takes place here is: on attachEvents we set mouseenter and mouseleave to point to the special methods we will create to show or hide the tip respectively. Because these two methods need to keep the scope to the class instance, we bind them to ‘this’. Because we need to be able to remove the tooltips from an element and clean up the events, we store a reference to the bound functions into the class instance so that detachEvents can find the callbacks and remove them (in this.boundEvents).

We are happy now, we can create the class and attach events to it. So here are the two functions that deal with showing and hiding the tip:

showTip: function() {
    // triggered on mousenter or called direct

    // fire onBeforeShow
    this.fireEvent("beforeShow");

    // next event will be onShow through morph onComplete
    this.event = "show";

    // animate properties
    this.tip.morph({
        marginTop: [-this.options.topOffsetStart, -this.options.topOffset],
        opacity: [0, 1]
    });
    return this;
}, // end showTip

hideTip: function() {
    // triggered on mouseleave ot called direct

    // fire onBeforeHide
    this.fireEvent("beforeHide");

    // next morph event will be hide
    this.event = "hide";

    // hide animation
    this.tip.morph({
        marginTop: -this.options.topOffsetStart,
        opacity: [1, 0]
    });
    return this;
} // end hideTip

The first thing we do is we fire off the ‘before’ events. This can tell the instance we are about to start animating the tooltip into view or out of view. Why is this useful? You may want to modify your trigger element and make it an ajax spinner, change some content, modal your screen or even request data from ajax to show later.

this.event = “show”; is a little hook that allows us to pass back to the Fx.Morph onComplete event which event to fire next, in this case onShow. To the instance, that event says, ‘animation is complete and tip is in full view’. One thing you can do here is, for example, passing this to the options when instantiating the Class:

onShow: function() {
    this.setTitle("").setHTML("loading...");
    var self = this;
    new Request({
        url: "someurl.php",
        onComplete: function() {
            self.setHTML(this.response.text);
        }
    }).send("view=getTip&id=" + this.element.get("data-id"));
}

… will fetch some data from an ajax view with some params and then set the tip body text to the response.

The hideTip fires the opposite events, onBeforeHide and onHide. An example use case for onHide can be to make it a one-off tip and remove the tippable after it has been seen:

onHide: {
    this.deatchEvents();
}

And done! Subsequent mouseenters on that element will no longer trigger a tooltip.

That’s it, in a nutshell. You have just created your new MooTools Class and can start using it. Look at the jsfiddle for this tutorial, it is somewhat important to look at the CSS that accompanies the Class:
http://jsfiddle.net/dimitar/WUfNR/. You can also see the events at work (look at your console) and try a a double-click on a trigger image to disable the class.

Any questions, you can always find me on #mootools on irc.freenode.net (nick coda- or d_mitar) or… just ask. I am sure somebody will be there to help. Have fun


Mar 10th 2011 × The MooTools Round-up, week 1 (7 – 13th of March)

Going to start a new series in the blog on everything MooTools on a weekly basis. If you notice how “Round-up” plays on the cows element, that’s no accident. Only wish I was called ‘Woody’. Oh well.

So, what’s new in the world of the greatest javascript framework known to man?

My pick of the latest MooTools plug-ins

  1. Fx.CSS by @tbela99 is a nice class that makes the base MooTools Fx Class compatible with CSS3 transitions and effects. Looks like a very comprehensive effort, a must-see for those that try to phase out Flash.
  2. inPlaceEditor, also by @tbela99 makes for easy on-page editing of elements (contenteditable, cough)
  3. Time by Arieh Glazer gives you rails-like syntax for stating times
  4. Powertools::history by @cpojer of mootools-core is my pick of the litter – giving hashchange or popstate history management with graceful degradation to suit your ajax app needs.

IRC quote of the week
This is meant to be a joke so please be warned.

<kentaromiura> a mootoolist and a jqueryist walks into a bar, the jqueryist throws $ at the bartender while the mootoolist order a new Beer with more class.

For more classic moments like these, visit the MooTools IRC channel #mootools on irc.freenode.net and wait for kentaro’s next show.

Whine of the week
Popular tweets by people that have seriously failed to get the MooTools to works and make teh accordions!

@vgrovestine “IE9 not compatible with MooTools. Color me unimpressed.”
**update, new leader for the week**
@sergio_martino “Mootools has no Live event bindings… how crap is this js library… #mootools #usejquery”

Scoop of the week
Whilst discussing private methods in MooTools Classes, which currently works through the undocumented `.protect()` function decorator, Arian said that MooTools 2 will be getting a public API for it looking like so:

var foo = new Class({
    "private bar": function() {
        alert("this be private");
    },
    realBar: function() {
        this.bar();
    }
});
var myFoo = new foo();
myFoo.bar(); // exception
myFoo.realBar(): // ok

I guess that’s one way to go with it. Another speculation had been a mutator like in Class.Binds: Private: ["bar"]. Apparently, you will be able to control this by writing a regexp mutator yourself and get it to behave like python or whatever takes your fancy.

Tutorial or blog post of the week
This week I came across a great post / overview of MooTools by Jonathan Krause, albeit written in German. http://www.jonathan-krause.de/artikel/mootools/ is the URL if you know German, trust Google Translate or just want to look at the code and the pretty pictures instead.

And another article I came across that’s slightly older but nice none-the-less: 12 Steps to MooTools Mastery by the MooTools team member I am afraid to admit I know least about, Jacob Thornton.

JavaScript fun
In case you missed it, here’s the most unique game of its type: a hashtag URL ascii char chaser game (called URL Hunter, really). Enjoy.


Feb 18th 2011 × Compressing jpeg images via base64 data and gzip deflating

Jpeg images are already fairly compressed. Applying gzip inflate/deflate to them does not gain much whereas gzipping files with a text content type (.css, .js, .html) usually gives pretty good results. This all led me to think, what happens if I take a decent sized jpeg image, convert it to a data:image base64 set and stick it in a dedicated css file. It will then be crunched by apache and much less data should be sent to the client browser.

So much for the theory. Here’s the actual test file.
http://fragged.org/dev/base64.html

- testing with image: http://fragged.org/dev/map-shot.jpg -133.6Kb
- dedicated CSS file: http://fragged.org/dev/base64.css -178.1Kb
- GZIP encoding server side enabled.

Resulting size sent to client (YSLOW components test): 59.3Kb! That’s a whopping saving of 74.3Kb – less data is being sent to the browser and most importantly, the jpeg quality remains the unchanged.

yslow components

Just a thought… I wish IE6 supported base64.


Dec 17th 2010 × Rant on wordpress updates and plugins that bundle jquery

I updated WordPress yesterday and did I come to regret it… It deleted all post cache and the ‘WordPress Popular Posts’ plugin stopped working. Whilst I was looking into it, I noticed it was bundling jQuery into the page. What’s worse, the plugin does not seem to function / record article views when jQuery is disabled (all the visual animations are custom MooTools code so this makes no sense…). Time to look for an alternative but for now, this blog will be bundling 2 frameworks (for which I am deeply sorry).

no

Dec 17th 2010 × Intermoos part 5: Ryan “rpflo” Florence. On moo4q and ninjas

Here’s the next instalment in our Intermoos series: we sit and talk with Ryan Florence, one of the most extraordinary and well respected coders, the man behind moo4q, SlideShow, mooDocs and the MooTools magazine. I thought he was Italian (or at least French) for a long time. I was wrong…

Name: Ryan Florence
Nickname: rpflo
Country: USA
MooTools team: none / occasional contributor
Age: 29
Company / Occupation: Clock Four / Senior Technical Consultant
Blog: http://ryanflorence.com/
Website(s): http://moodocs.net
Twitter: @ryanflorence
GitHub: https://github.com/rpflorence
Famous for: The blog, the magazine, moo4q, SlideShow, MooDocs
A little bit about yourself and your background…
I live in Salt Lake City, UT with my wife and two kids (a 3 year-old iPad addict daughter, and a chubby 3 month old boy). I work from home for the bay area creative agency, Clock Four doing mostly front-end development.
How and when did you get involved with JavaScript and MooTools?
My first real job was back in the 90′s cranking out websites as a teenager for a local ISP. I tried to learn C++ in 21 days but couldn’t get past the second chapter. About the time Java applets started popping up on websites the ISP went broke. I had no interest in programming and started selling decals I made at school online (people actually mailed me hand-written checks!)

After college I was in sales, and eventually ended up working as an implementation consultant for PolicyTech, renewing my interest in web development. Dissatisfied with quickbooks on my Mac I decided I’d learn how to write a web application in PHP and JavaScript to handle my invoicing and accounting. I found scriptaculous first, but couldn’t get some animations to quit bumping into each other; then I found MooTools and its genius Fx module. I was still clueless though, mind you.

Shortly after this, MooTools 1.2 came out. The new documentation flipped a switch in my brain or something. Suddenly the concepts of objects and classes made sense. I rewrote my invoicing application as a single page, desktop-esque, ajax heavy, ridiculously awesome tool that I still use today. As I dug deeper into MooTools I accidentally uncovered a pot of golden, vanilla JavaScript knowledge.

Being self-taught, I put a high value on documentation. I wrote MooDocs to document and release my scripts and provide a way for others to share theirs (no forge yet). That site earned me an invitation into the MooTools developers circle and I’ve held the “MooTools FTW” banner ever since.
You seem to have an apprehension of MooTools that is very hard to beat and champion it daily. Why MooTools though, was it love at first sight or did you jump over from another framework?
Oddly enough, MooTools was my first programming “language”. It was my programming university–it taught me to focus on the API, test my code, and program patterns rather than implementations. Now I view everything else with that bias, whether it’s jQuery, Ruby, or Objective-C.

I stick with MooTools for two reasons. First, I love JavaScript. The Type extensions allow me to write clean, natural JavaScript–no screwing around with namespaces and abstractions that hide the language: arr.include(item) versus ns.utils.array.include(arr, item). Second, I love classical inheritance, and object templates. My brain is naturally wired to think that way. The world around me is designed that way–dogs inherit from mammals. The end goal is to reuse code, which I can’t seem to do as well with differential inheritance–which is like, Siamese twins can share the same legs, right?
I know you’re also a bit of a jQuery user (cough) and in trying to make it more usable and scalable, you created moo4 – a project that brings MooTools Class to jQuery. How is that going and do you think it can ever be considered stable and reliable enough to be used as the basis of serious Web App development under jQuery?
Moo4q definitely elevated my reputation in the JavaScript community and was a lot of fun to figure out. It’s certainly stable, I’ve used it several times in production (it’s just a custom build of MooTools plus a small Class mutator). The site gets about 100 visits a day, mostly to the tutorial page, so I think there are a few folks actually using it.

As for using it in a serious application, I dunno. From a MooTool’s perspective you’re really just swapping out the Element, Fx and Request modules for jQuery–which doesn’t really offer you anything new or better than what MooTools already has. From a jQuery perspective, you have to learn so much about MooTools’ patterns, you might as well jump all the way in.

So you’re probably asking why it exists. I use it in two cases. 1) I’m stuck with jQuery and need to do something that I’ve already done in MooTools. I’ve found that usually 10% or less of my classes have to be adjusted to become moo4q classes. 2) I’m delivering templates to a client who only knows jQuery. I can still structure my stuff the way I like to, and they can do whatever they want with jQuery after delivery.
Do you think that having something like moo4q “out there” may dissuade users from swapping over to MooTools for more involved app building? It’s as if you have just taken away one of its biggest advantages and brought light to the blind (I am only half-joking, heh)…
Haha, yeah. Originally I had hopes of it being a gateway drug for jQuery users to eventually fully convert. But in the end, moo4q is mostly appealing as moo4-devs-stuck-with-q. I don’t think it hurts MooTools adoption, probably helps by showing outsiders quite plainly what it can do. It also serves as a solid demonstration of the scope difference between the two.
What are you working on at the moment (on the framework itself or related)?
Man, I think I have development ADD. Outside of outlining more articles for my site, I’ve been working on a lot of stuff. SlideShow 2.0 is a few commits away, which brings with it a handful of (awesome) improvements and performance gains, including CSS transitions.


Speaking of which, I just released CSSAnimation, a vanilla JavaScript implementation of CSS transforms and transitions–complete with MooTools and jQuery API extensions. It powers the new transitions in SlideShow.

Two new scripts I’ve been giving a lot of attention to are Channels and Element.Behaviors. Channels is an extended pub-sub pattern that allows you to completely decouple your objects from each other. Element.Behaviors lets you separate your JavaScript from the DOM. The two together have been a lot of fun to work with.


On the SSJS front, CrypticSwarm and I just started porting packager to packager-node. I’ve also recently written an alternative MooTools documentation browser as my first node project that I hope to make a whole lot better now that I’m learning more.
Are there any other Open Source technologies or projects you are involved with?
My website is built with nanoc, a static site generator built with Ruby. It’s surprisingly powerful, and has sped up my development process at work for building micro-sites and similar projects. Haven’t had the time to give back to the project, but I have some stuff I’d like to contribute.
If time and resources were not an issue, what new features or changes would you like to see most come into the framework or the website?
Core – MooTools Core has had the same API for 2 years (!), it was done right. But I’d love an ES5 shim with no dependencies and more modularity with the Type extensions. There’s a lot of those extensions in Core that are rarely used (string.hyphenate?). At least $chk is gone, which was useful for allowing 0.

UI – I’d love to have a UI library comparable to Dojo dijit.

Website – I think a node version of the forge will get a lot more interest and contributions from the community and packager support would be awesome. Also, I’ve been promising Darren my time to write a whole boat load demos to help the sorry demos page out.
If you had not been involved in MooTools, what do you think you’d be doing instead?
I’d still be flying around the country consulting people on how to manage their policies and procedures, making a whole lot less money. I owe just about everything about my current employment to the MooTools community. David Walsh is responsible for 50% of my twitter followers and website visitors, and is always a great sounding board for APIs I’m trying to develop for my plugins. I’ve learned almost everything I know about web development from everybody who hangs out in IRC (and Aaron Newton, who doesn’t). I owe a special thanks to Thomas Aylott, who got me my current job and has helped me understand JavaScript and web development more than he probably realizes. So yeah, without MooTools, I probably wouldn’t be a developer at all.

Dimitar: Yes, I need to get SubtleGradient to say a few words here too…
So, jQuery is the biggest framework out there but MooTools is sat prettily at the #2 spot. How do you envisage library evolution and the ‘scene’ in the future?
jQuery will remain #1. Like I said on twitter a while ago, most everything about jQuery is an implementation, making it ridiculously easy to learn. Even with the recent rebirth of JavaScript, most people making websites still don’t know, or care to know, the language. For them, jQuery is the obvious choice, and rightly so.

However, people are writing more JavaScript than ever and need more than just a DOM library. Alex Sexton has an awesome talk called jQuery’s best friends. He’s a smart, influential guy. I think his approach to pull in other tools outside of the jQuery scope is totally appropriate. We are already seeing the advanced jQuery users adopt this strategy.

On the flip side, you’ve got bright developers like Rebecca Murphey turning away from jQuery for their bigger projects. When jQuery users start feeling that “holy crap, what have I done?” feeling with their JavaScript, Dojo is the natural place to go. Just search and replace $ to dojo and you’re more than half way there. Nearly every jQuery method has a Dojo cognate. Also, both hang everything from a namespace. This makes it an easier transition than jQuery to MooTools. Add to that its incredible UI library and support and I’m quite sure Dojo will become the top library for non-trivial websites, if it isn’t already.


So what about MooTools? MooTools doesn’t seem to care a whole lot about adoption (look at our demos page), so I don’t see us making any sort of huge leap in market share. It’s a completely different paradigm. When all the books freak people out about extending the prototypes of Array and String, etc. or that “JavaScript doesn’t have classes” it adds a level of FUD that some just can’t get over. I do think, however, that our user base will continue to grow with really talented people.
This is a thorny subject but since you are a versatile programmer that can and does use multiple frameworks, how do you decide which one to include in your projects? What is your criteria/checklist?
Good question. Developers switch projects, contracts, and companies so often my motivation is mostly for the person stuck with my code a year from now, which boils down to support and documentation. MooTools is of course my default choice so I tend to ask myself these questions to justify not using it.

Who is going to maintain this code?
I write a lot of front-end templates for clients to implement into their CMS (or whatever). Once delivered, I’ll probably never see it again. Most of the time the client’s developers have little JavaScript experience outside of jQuery, so I use jQuery in these situations. If there are some really sophisticated specs, however, I’ll push the client to use MooTools, or just slip moo4q in the back door.
Do I need a UI library?
One word: dijit. It’s a part of the Dojo toolkit, well documented, and therefore likely to be supported well into the future. Everybody ought to spend an afternoon playing with Dojo dijit.

jQuery UI has a miserable API, so I’d never choose it.
MooTools doesn’t have an official UI library so you’re on your own to write and document an API, or you have to rely on plugins that may or may not have good support and documentation now or in the future. If it’s a personal project, however, MooTools, regardless.

Which browsers are supported?
Occasionally I get to work on something that only has to work in the newest browsers. In these cases I shed all the libraries and go commando with vanilla JavaScript.
What does the client dictate?
Sometimes I have to use jQuery, even if another choice would be better, because the client says so (ASP.NET, cough, shipswithit, cough). It’s not worth the fight and I like getting paid :D
If you could give one tip to new MooTools developers, what would it be? Aside from “Learn javascript”, that is?
Actually, I wouldn’t say “learn JavaScript.” When you learn MooTools, one day you’ll wake up and realize you’ve learned JavaScript.

That aside, I think my single tip would be read the source to the plugins in Core, More and the Forge (Core has some crazy JavaScript, but Fx.Tween is easy to understand). When you’re writing something that feels similar to something else, go read the source, see how they did it.
Your favourite MooTools website or plugin:
Website – jsFiddle. Plugin – SlideShow. I know it’s my own, but it is so useful for content that shares the same space (not just slideshows) I often forget that I wrote it.
Your top 5 resources for web developers (can be websites like jsFiddle, IDEs, tutorials, CSS frameworks like boilerplate, etc)
  1. Google
  2. Your editor’s documentation
  3. People, mentors, mailing lists, IRC
  4. Modernizr
  5. Early morning hacking–your mind solves the problems in your sleep, dead serious
Do you have any example sites you want to share / show off? I saw you mention the launch of new one the other day?
We just launched a new site for Capital One, advertising their student credit card, Journey. I had some extra time so I screwed around with 3D transforms and CSS transitions on the credit-101 page (safari only). It’s this project that led to Element.Behaviors and CSSAnimation.
You’ve certainly hacked a few interesting solutions recently and I am still searching for the first MooTools self-confessed ninja, is that you?
No, not me, although I did create this. All of my code is pretty much beginner’s luck, which is not the way of the ninja.

Is that your ostridge there? Thanks for your time!


Dec 14th 2010 × Intermoos series, part 3: “ketching up” with Christoph Pojer

Another day, another “intermoo”. I really wanted to get Justin Bieber to comment on MooTools today but seeing as he refused to commit to answering my questions, I got the next best thing: the chance to ketchup[1] with Christoph Pojer from the MooTools core team.

When you meet with Chris, there’s something endearing about him, and it’s not just the way he says ‘mutuulz’ (you can watch this talk on mootools Chris gave earlier this year and see what I mean). We try to find out what drives him on today.

Name: Christoph Pojer
Nickname: cpojer
Country: Austria
Occupation: Student of Software Engineering and Business Administration
Blog: http://cpojer.net/
Twitter: @cpojer
GitHub: http://github.com/cpojer
Famous for: MooTools Core Developer, PowerTools!, small height
A little bit about yourself, your background…
I am 21 years old and I live in the wonderful city of Graz in Austria. I am a student of Software Engineering and Business Administration at the Graz University of Technology. I would define myself as (Mobile) Web (Application) Developer and I am active on the Internet for as long as I have a connection – that’s about ten years now!
How and when did you get involved with MooTools?
When I started with web development I started using JavaScript. I didn’t learn the language at first but when JavaScript and XHR got more widespread adoption later in 2005 I started building my own little animation library. Shortly after I found moo.fx and I became a frequent reader of the mad4milk blog – the place where “moo.dom” and “moo.ajax” were released which eventually lead to MooTools. I was a MooTools user since the famous 0.87 version and I remember bugging Valerio to include “DOMReady” back in the days. I stuck around and got to know the core developers but only a few years later I started to actively contribute and eventually I became a member of the Core Development Team.
Why MooTools, what makes it special?
The module that got me using MooTools was Class.js. Back in the days we didn’t even have inheritance or mixins but given that I was unaware of the prototype-based nature of JavaScript, Class made me feel like home. Ever since, I love how MooTools works, the abstractions and the clean code, just great. However, at the moment, the most important part about it is our community. I actually got to know and got to meet a lot of the MooTools developers and they have all become great friends.
What are you working on at the moment (on the framework itself, related or otherwise)?
Right now I am doing lots of probability theory, object oriented analysis, data structures and algorithms, software architecture and information security related stuff. That, of course, doesn’t have anything to do with MooTools but during the semester I don’t have time for anything else really. But fear not, in the web assignments I am of course making use of MooTools (and PowerTools! ;) ). Recently I did some experiments with DeviceOrientation and DeviceMotion on iOS 4.2 (see http://twitter.com/#!/cpojer/status/7485711225716736).
Are there any other Open Source technologies or projects you are involved with?
You can usually find me doing work around the JavaScript eco-system. Therefore I am involved in a number of minor projects, nothing similar to MooTools. I am involved with GitHub. It makes the development experience so much better and more fun – it is easy to contribute to almost anything.
You have recently done some amazing work on the MooTools PowerTools! which help a fair bit in making the framework portable on all handheld devices. Do you see the role of internet phones grow and the need for proper portable javascript support to go with it? Are there plans to port some of your work into the MooTools core or more?
The goal of PowerTools! is not to make MooTools mobile compliant – MooTools works great on mobile devices already. One part of PowerTools! is the mootools-mobile project, which brings custom gestures and more for your mobile web app. PowerTools! is about providing low-level MooTools extensions or HTML5 related plugins that help you speed up the development process or to make your code more maintainable. As far as mobile is concerned, yes – mobile browsers have a lot of catching up to do, but we will get there. The mobile web is definitely important. PowerTools! is currently standalone and there are no plans to officially include it with MooTools. I don’t want to bloat our beloved library ;)
Would you share your thoughts on what the future holds in terms of HTML5, CSS3, V8, next gen browsers, server-side javascript, the role of frameworks and MooTools in web application development?
Oh well, there are a lot of buzz-words in there. I honestly have no idea, unless you have time to read five different scenarios on how the future might turn out? Haha, I thought so. Seriously speaking, it’s difficult to say. I think its reasonable to say that the amount of abstractions will increase and a lot of things will get easier even though under the hood they become much more complex. It’s just the beginning. And also, it’s just JavaScript.
If time and resources were not an issue, what new features or changes would you like to see most come into the framework or the website?
MooTools 2.0 of course! The whole thing will blow your mind, once its done of course :P
If you had not been involved in MooTools, what do you think you’d be doing instead?
Well, that would mean I would not be involved with anything related to the Web. I’d probably just go for a BA masters, but that would be the most boring thing… In any case, without MooTools my life would be very different, not nearly as awesome as it is right now and I wouldn’t have made so many great friends – I am really grateful. Also, the word “Ping!” would not make me laugh, Djamil wouldn’t be a funny person and ketchup would just be ketchup.



**editor** [1] to fully appreciate what he’s saying, you really have to see the MooTools core team eat burgers, chips and ketchup, or rather, have some food with their ketchup. Failing that, you can always login to IRC and “ping” cpojer, he loves it!

MooTools is now officially the 2nd largest framework / library out there, how do you think it will grow from here?
The numbers vary, I am not so sure about their correctness. MooTools is being used a lot behind the scenes – in huge internal applications. That is where I see MooTools. If you want to do serious web applications, MooTools is the obvious choice. Given that we are moving to a “Web of Apps”, MooTools has a good starting place. Let’s see where the journey will go.
If you could give one tip to new MooTools / javascript developers, what would it be?
What I have found is that most Web Developers still do not have an idea of what they are really doing. My advice is to learn the core concepts, learn about how the Web works, learn about object oriented languages, learn JavaScript. If you know the basics it only gets easier and a whole new world opens up every time you learn something new. MooTools can help you hide the complexity behind JavaScript and makes it easier to get started. Also, don’t be afraid to ask questions. It is what I do all the time when I want to learn something. Join the #mootools IRC channel on Freenode and ping me (cpojer), I’m happy to help!
Your favourite MooTools website:
I don’t usually have one. If you want to learn MooTools then go to David Walsh’s (FTW) website http://davidwalsh.name/ – also, the site is awesome for using the hover-effect on links which I created :) Some people claim David stole them, I refuse to believe that.
Your top 5 resources for web developers (can be websites like jsFiddle, IDEs, tutorials, CSS frameworks like boilerplate, etc)
GitHub. MooTools.net. PowerTools!. NetBeans. Chrome Web Inspector.

Thank you for your time!


Dec 13th 2010 × Intermoo series, Part 2: Piotr “Zalun” Zalewa, jsFiddle creator

Here’s “Intermoos“, part two: we sit and talk to Piotr Zalewa, aka Zalun of jsFiddle fame. If you’ve not heard of jsFiddle or used it, you should stop reading this and visit it first, play with it and come back because you’d be missing out.

Whereas Zalun is not an official MooTools team member, his contribution to the MooTools community (and to the javascript community at large) through jsFiddle has been nothing short of outstanding. Oh, and yes, he prefers and uses MooTools. So here we go…

Name: Piotr Zalewa
Nickname: zalun
Country: Poland
Company: Mozilla
Blog: http://piotr.zalewa.info/
Website(s): http://jsfiddle.net/, http://builder.addons.mozilla.org/
Twitter: @zalun
GitHub: http://github.com/zalun
Famous for: mooshell and jsfiddle
A little bit about yourself, your background…
I am a father, an aquarist and a web developer. I enjoy designing and maintaining my never too big “nature style” aquarium. I like watching my children grow and learn. I also like free stuff a lot. That’s why I created jsFiddle and didn’t hesitate too long to join Mozilla Team.

I started programming when I was 19. It was Turbo Pascal on XT’s and AT’s. At university I realised I like Gopher, IRC and FTP. Then in our university library someone placed 3 public computers connected to the new thing called World Wide Web. I was usually not consuming the content, but looking at how it was build. Soon I had my own website…

How and when did you get involved with MooTools or javascript?
I was hired by Moving Picture Company to create an intranet tool for movie management. They gave 10 working days to find out the best technology for the front-end. On the back-end Django was set from beginning. I was investigating all possible JavaScript frameworks and MooTools was something which I found the best, although I didn’t know anything about it at day 0.
Why MooTools, what makes it special?
Classes, clean code, ability to shape things in a way developer wants. I found a lot similarities to Python which is good as I write back-end in this language. I think it’s the best tool for someone who writes code, not only uses plugins.
What are you working on at the moment (on the framework itself, related or otherwise)?
I’d like to make Accordion better. It is considered as a bad UX, but I can’t imagine jsFiddle without it. I also started to rewrite jsFiddle – beta is coming (we aim for January). There is also another launch coming at Mozilla. We would like to have the Addon Builder 1.0 ready for the Firefox 4.0.
Are there any other Open Source technologies or projects you are involved with?
FlightDeck is open-source (as whole Mozilla), otherwise nothing I could call “involved”.
You have arguably created the most useful / groundbreaking tool for online collaborative javascript / web development testing to come out recently in jsFiddle. What gave you the idea and prompted you to do it?
I needed it. I would guess it’s the most honest answer for majority of start-ups. I was on #mootools IRC channel and we were helping new users with JavaScript/MooTools issues. We were even playing who will answer first, but the rule was – code has to fit in one line. Soon there was a question which was longer then that – although we do have pastebin I wanted to check if my idea was right before posting. I thought creating file with right DocType, including files and then loading into the browser was too much trouble. The question remained unanswered, but the next day I had a working prototype.

Just as a side note – jsFiddle wouldn’t be as awesome if not help from Oskar Krawczyk who is the “front-end guy” and other members mostly around MooToos community. Thank you all very much.

What technologies power jsFiddle? How is it holding up with the huge attention and traffic it is getting, particularly due to MooTools and jQuery adopting it as the de-facto platform for testing and case building / examples?
Back-end is all Django, MySQL and memcache. It still uses Apache, but I think beta will run from within Nginx or something similar. On the front-end we do use MooTools with a bunch of plugins such as ClientCide. CodeMirror is highlighting the code.
jsFiddle started off from mooShell, a tool initially MooTools specific and Open Sourced. Does that mean that mooShell development has now ended and do you have any plans for Open Sourcing jsFiddle?
Yes – mooShell will be closed when jsFiddle beta will start. It is currently in read only mode. I am still uncertain what type of license should I use for the new jsFiddle. It is a rewrite… I’d like to make it open source, but the business model I have in mind might be against it.
What future plans can you reveal about changes and growth for jsFiddle? Anything exciting you would like to share? That ‘business model’, perhaps?
I think the most awaited is user profile with ability to personalize jsFiddle – change editor application (there is a choice now!), the way it displays code, manage the framework drop down, etc. We will also add PRO accounts with many features around private fiddles.
What requirements do you have for accepting a new framework and how should development teams approach you about getting added?
This is a hard question – it’s mostly the community behind the project. We tried to add every framework which is a “must have”. There are few exceptions (like Processing js or Raphael which aren’t even frameworks), which we simply wanted to use. Beta version will be more specified and with the ability to tweak the “hot list” we will be able to implement much more frameworks. Some will be simply hidden by default. I am also adding the “Framework manager” badge. Users with such privileges will be able to maintain the framework – upload/link new versions, add best plugins, etc. More power for the users.
If time and resources were not an issue, what new features or changes would you like to change or refactor and why?
The way the dependencies and frameworks are bond together is wrong – this is invisible for the end-user, but adding new version of the framework is currently a pain.

On the front-end side – it would be fixing the layout for small touch screen devices.

If you had not been involved in jsFiddle, what do you think you’d be doing instead? I know you are currently working for Mozilla on JetPack, would you like to comment on that and give us an overview?
I had a few other ideas in mind, but these needed much more work on the beginning, which is a pain for free projects – not enough hype.

“Jetpack” is a working name for the new Firefox add-ons type. Firefox 4 will have it build in. It allows to install add-ons without restarting and is really easy to write. CommonJS style. SDK currently uses Python (I think it will use NodeJS in the future) and involves some work to be done to install on the developers computer. Mozilla thought it would be good to make this a lot easier and the idea for Addon Builder aka FlightDeck arised. It could be name jsFiddle for Firefox Addons. Users are able to edit and test addons without leaving the browser.

If you could give one tip to new javascript developers, what would it be?
JavaScript developer to me is a person who writes the code – classes, plugins. The knowledge of vanilla JavaScript is essential. So the tip would be – learn vanilla JavaScript. If I would be able to give another it would be: read framework’s code. It is interesting and enlightening.
Your top 5 resources for web developers (can be websites like jsfiddle, IDEs, tutorials, CSS frameworks like boilerplate, etc)
Github, documentation sites from framework developers, VIM, IRC, Linux, Twitter. I don’t need much :)
If you want to share some examples of your work…
It would be http://webdev.zalewa.info/. It’s a really old site, half of the examples there are from the time when I thought I could be a web designer, but clearly I’m not made for it. I guess you’ll find quite a few 404 on it as well.

Thank you for your time!


Jul 19th 2010 × summer outdoor sandals blues

This is nothing to do with javascript but I am on a holiday, after all…

Bit gutted to find that my otherwise excellent Newport Sandals by Keen have started to pack it in after 2 seasons of tear and wear – it seems they were not as water resistant as I was initially led to believe. Nasty side effect – the leather now stinks so bad (due to getting wet a few times) I cannot wear them inside my car. Such a shame, I really really really liked them…

keen newport sandals

What to buy now or do I just order another pair? Hrm…


Mar 31st 2010 × mooSelecta – an accessible mootools select/dropdown element replacement

Don’t you just love how different browsers style (or rather, don’t style) select and option elements? One of the things I dread most as a developer is when the design team come in and produce forms with controls that are totally bespoke and unobtainable due to the browser limitations.

This prompted me to write a mootools class that replaces the existing select items on the page with custom style-able controls through CSS as a progressive enhancement. Here is an example of what the resulting dropdowns can look like:

mooSelecta dropdowns screenshot

The idea of skinnable dropdowns is nothing new but not many solutions are done in a way that mimics the select element’s behaviour and events correctly. Here is what mooSelecta does feature:

  • support for any type of skins, all through CSS
  • support for native element events (will work with scripting)
  • support for keyboard look-ups when dropdown is open
  • support for input labels
  • support for tabindex

Have a look on the mooSelecta example page or on the mootools forge page for the plug-in itself (download etc).

One thing you need to be aware of is that if you want to dynamically change the selected value of a skinned select, you need to fire it’s onChange event for mooSelecta to update. For example, if you have a dropdown with id=”country” and class=”selecta”:

new mooSelecta({
    selector: "selecta"
});

// change default selected value via js later:
$("country").set("value", "United Kingdom").fireEvent("change");
// the event will make mooSelecta update

Aside from that, it’s fine, tested and working in IE6, IE7, IE8, Firefox 2, Firefox 3.6, Safari 4, Chrominum 5. Known issues with Opera keyboard events not being raised as expected. Enjoy!


Feb 17th 2010 × Site optimisations, CDN and the hidden bandwith costs of cookies

Around Christmas we tend to get a LOT of web traffic at work, so much so that we exceed our agreed bandwith a allocation with RackSpace and end up having to pay huge excess fees. Not wanting to be caught out for a second year in a row, I had a look at various ways of conserving bandwith and alleviating from the CPU load on the webserver. This is when I noticed something odd–there was a lot of traffic we were being charged for that was not showing up through the Apache logs. After a lot of head scratching and many coffees later, it hit me: cookies. Consider this: an average user on our site has something between 300bytes and 1k in cookie data (a lot, I know). The cookies are being sent alongside with every resource that the client browser requests, be it a HTML file, an image, a CSS stylesheet or a .js file. I did some rough maths and it transpired we waste between 10 and 20GB of traffic each month in cookies alone!

Additionally, the CPU usage was abnormally high and no amount of MySQL tweaking was cutting the load times enough to make a sizeable difference. The sheer amount of files accessed and served was taking its toll and limited CSS spriting was just not going to fix that. The clincher came from Google who announced that site speed is to be playing a role in the search engine results pages from 2010–it was time to introduce a content delivery network (CDN) and fix things.

I had a look around at what CDN providers were around but since we are a relatively small and lean startup, we could not justify the expense of signing up for a enterprise scale solution just yet and yet we needed real-time updates. We elected to just get a cheap collocation server instead with no bandwith quota and setup a sub-domain cdn.ourdomain.com which was to remain cookieless. I then reconfigured the site templates to always reference images, css and js through the CDN URL instead and setup an rsync partnership with the new box. And boy, did that make a difference!

First thing you notice now is how much more responsive the site is, how quick it loads and how much faster the browser renders the content due to the increased threading capability. The CPU load times dropped from an average of 1.40 to 0.30. Out bandwith use subsided from well in excess of 200GB a month to a little over 100GB, well within our quota. And that’s through a ‘pseudo’ CDN, or should I call it a CDB (content delivery box). I imagine the user experience will improve even further when we can roll out a proper solution in the near future, one that will use CDN zoning to provide the fastest download speed to clients through geolocation.

In the meanwhile, I was approached by the folks at MaxCDN who kindly offered to sponsor my blog and provide it with a CDN. I thought, what better chance to test the experience and find out about what’s on offer than to try it for free…

I was uncertain as to how easy it would be to implement within WordPress but it turned out to be a walk in the park through the plug-in W3 Total Cache that they provide and support. The whole setup involved all of 5 minutes of work and no changes to my template files (so long as they all reference the native WP functions for URLs). The plugin takes care of sync and you really have nothing to do than to worry about caching. I am still getting to grips with the options here and weighing in what further bits can be exported to maxcdn in addition to my static content. Other than that, it’s been a breeze and has probably sped up my blog a fair bit too. It’s also surprisingly affordable, especially when you consider what Akamai, EdgeCast or Limelight tend to charge. Even cheaper than CacheFly for the basic package without rsync functionality. MaxCDN’s site, control panel and support are also nothing but excellent.

All-in-all, I am a happy chappy and would recommend CDN use as it’s become a lot more accessible (to my surprise).