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 3D Folding Animation

    Google Plus provides loads of inspiration for front-end developers, especially when it comes to the CSS and JavaScript wonders they create. Last year I duplicated their incredible PhotoStack effect with both MooTools and pure CSS; this time I'm going to duplicate...

  • By
    Send Text Messages with PHP

    Kids these days, I tell ya.  All they care about is the technology.  The video games.  The bottled water.  Oh, and the texting, always the texting.  Back in my day, all we had was...OK, I had all of these things too.  But I still don't get...

Incredible Demos

  • By
    Using jQuery and MooTools Together

    There's yet another reason to master more than one JavaScript library: you can use some of them together! Since MooTools is prototype-based and jQuery is not, jQuery and MooTools may be used together on the same page. The XHTML and JavaScript jQuery is namespaced so the...

  • By
    Truly Responsive Images with responsive-images.js

    Responsive web design is something you hear a lot about these days. The moment I really started to get into responsive design was a few months ago when I started to realise that 'responsive' is not just about scaling your websites to the size of your...

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!