MooTools Tip: Class.toElement

By  on  

Many of you may not know of a feature that's baked into MooTools' Class internals: Class.toElement. Class.toElement allows you to pass the $ (or document.id) method an instance of your class and the instance will be treated as an element.

The MooTools Class.toElement Usage

/* baking into the class */
var myClass = new Class({
	initialize: function(container,options) {
		this.container = $(container);
	},
	// .. lots more methods //
	toElement: function() {
		return this.container;
	}
});

/* usage */
var mc = new MyClass('wrapper');
$(mc).fade('out'); //fades the container out

This isn't a groundbreaking piece of code but it's just another example of the flexibility that MooTools affords its developers. Happy coding!

Recent Features

  • By
    CSS Filters

    CSS filter support recently landed within WebKit nightlies. CSS filters provide a method for modifying the rendering of a basic DOM element, image, or video. CSS filters allow for blurring, warping, and modifying the color intensity of elements. Let's have...

  • By
    7 Essential JavaScript Functions

    I remember the early days of JavaScript where you needed a simple function for just about everything because the browser vendors implemented features differently, and not just edge features, basic features, like addEventListener and attachEvent.  Times have changed but there are still a few functions each developer should...

Incredible Demos

  • By
    Introducing MooTools ScrollSide

    This post is a proof of concept post -- the functionality is yet to be perfected. Picture this: you've found yourself on a website that uses horizontal scrolling instead of vertical scrolling. It's an artistic site so you accept that the site scrolls left to right.

  • By
    MooTools 1.2 Image Protector: dwProtector

    Image protection is a hot topic on the net these days, and why shouldn't it be? If you spent two hours designing an awesome graphic, would you want it ripped of in matter of seconds? Hell no! That's why I've created an image...

Discussion

  1. Haven’t noticed this wonderful tiny yet so useful method before. Thanks for bringing this up :)

  2. jeremy

    i was actually just reading about this today.

    it seems often times the method is used to create the element that gets returned as well, in which case its important to make sure the method doesn’t re-define the element it returns.

    toElement: function() {
    if (this.element) return this element;
    return this.element = new Element(...);
    }
    
  3. Hey, that’s a useful thing! Didn’t know this before, THX for sharing!

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!